Java String length() Method with examples

Java String length() method is used to find out the length of a String. This method counts the number of characters in a String including the white spaces and returns the count.

Java String length() Method

int length()

This method returns an integer number which represents the number of characters (length) in a given string including white spaces.

String length limit: The maximum length a string can have is: 231-1.

Java String length() Method example

In this example we have three different Strings and we are finding out the length of them using length() method

public class LengthExample{
   public static void main(String args[]) {
       String str1= new String("Test String");
       String str2= new String("Chaitanya");
       String str3= new String("BeginnersBook");
       System.out.println("Length of str1:"+str1.length());
       System.out.println("Length of str2:"+str2.length());
       System.out.println("Length of str3:"+str3.length());
   }
}

Output:

Length of str1:11
Length of str2:9
Length of str3:13

Java String length() method to calculate the length of String without spaces

As we have already seen in the above example that this method counts the white spaces while counting the number of characters in a given string. In case if you only want to count the number of characters in a string excluding white spaces then you can do so by using the string replace method as shown in the example below.

Here we are omitting the spaces in the given String using replace method and then using the length() method on it.

Here we are replacing all the whitespaces with nothing (removing them) using the replace() method and then using the length method on the updated string.

public class JavaExample {
   public static void main(String[] args) {
	String str = "hi guys    this is a string";
		
	//length of the String
	System.out.println("Length of the String: "+str.length());
		
	//length of the String without white spaces
	System.out.println("Length of String without spaces: "+
	str.replace(" ", "").length());
   }
}

Output:
Java String length() method example