Home Tutorial Java Core Java : Length of String

 
 

Share on Google+Share on Google+
Java : Length of String
Posted on: November 23, 2012 at 12:00 AM
Advertisement
In this tutorial we are going to write logic to count the length of specified String.

Java : Length of String

In this tutorial we are going to write logic to count the length of specified String.

Length of String : Length of string means the number of characters in your String. There is many way to find out the length of specified String. You can use String method to calculate length directly or you can write your own logic.

Example : In this example we are writing different way of finding the length of String str.

class StringLength {
	public static void main(String[] args) {
		String str = "Hello Roseindia";
		int count = 0;
		/* String method to print length of String */
		 System.out.println("Length of str : "+str.length());
		 System.out.println("Length of str : "+str.lastIndexOf(""));

		/* Simple logic to count length of String */
		for (char c : str.toCharArray()) {
			count++;
		}
		System.out.println("Length of str : " + count);
		/* Another way of counting length of String */
		int i = 0;
		try {
			while (true) {
				str.charAt(i);
				i++;
			}
		} catch (IndexOutOfBoundsException e) {
			System.out.println("Length of str : " + i);
		}

	}
}

Output :

Length of str : 15
Length of str : 15
Length of str : 15
Length of str : 15
Advertisement

Related Tags for Java : Length of String:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 23, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com