Java String length() Method

      No Comments on Java String length() Method




Java String length() method is used to find the length of a String. Basically, it counts the number of characters of a String.

e.g. String str = “HelloWorld”;
int lengthOfString = str.length();

The value of lengthOfString will be 10 as there are 10 characters present in the string.

Internal Implementation of the String length() method:

Internal Implementation of length() method in the String class is as below:

    public int length() {
        return value.length;
    }

Signature of String length() method:

public int length()

Let’s take some demo examples for length() method of String.

Example 1 : Java String length() Method

package com.masterjavatutorial;

public class Test {
   public static void main(String[] args) {
      String str ="Hello World";
      System.out.println("Length of Given String="+str.length());  		
   }
}

Space is also counted in the length of a String.
Output of the above program is as below:

Length of Given String=11

Example 2 : Java String length() Method – Length of Empty and Blank String

package com.masterjavatutorial;

public class Test {
   public static void main(String[] args) {
      String str =" ";
      System.out.println("Length of empty String="+str.length());  		
      String str1 ="";
      System.out.println("Length of blank String="+str1.length());  		

   }
}

Output of the above program is as below:

Length of empty String=1
Length of blank String=0

Leave a Reply