Open In App

Java String length() Method

Last Updated : 23 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

String length() method in Java returns the length of the string. In this article, we will see how to find the length of a string using the String length() method.

Example:

class Geeks {
    public static void main(String[] args){

        String s1 = "abcd";
        System.out.println(s1.length());

        String s2 = "";
        System.out.println(s2.length());

        String s3 = "a";
        System.out.println(s3.length());
    }
}

Output
4
0
1

Important Points:

  • The length() method returns the number of characters present in the string.
  • Suitable for string objects but not for arrays. 
  • Can also be used for StringBuilder and StringBuffer classes.
  • It is a public member method.
  • Any object of the String class, StringBuilder class, and StringBuffer class can access the length() method using the ( . ) dot operator.

public int length()

Return Type: The return type of the length() method is int.

Examples of Java String length() Method

1. Use of length() method to find size of String

public class Geeks {
    public static void main(String[] args){
      
        // Here str is a string object
        String str = "GeeksforGeeks";

        System.out.println(str.length());
    }
}

Output
The size of the String is 13

2. Compare the size of two Strings  

// whether the length of two strings is
// equal or not using the length() method
import java.io.*;

class Geeks {
    public static void main(String[] args) {

        String s1 = "abc";
        String s2 = "xyz";

        // storing the length of both the
        // strings in int variables
        int len1 = s1.length();
        int len2 = s2.length();

        // checking whether the length of
        // the strings is equal or not
        if (len1 == len2) {
            System.out.println("The length of both the strings"+ " are equal and is "+ len1);
        }
        else {
            System.out.println("The length of both the strings"+ " are not equal");
        }
    }
}

Output
The length of both the strings are equal and is 3


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg