Home Tutorial Java Core Java : Length of String

 
 

Java : Length of String
Posted on: November 23, 2012 at 12:00 AM
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

Related Tags for Java : Length of String:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.