How to determine length or size of a String in Java?

Below are the various methods to get the length or size of Strings in Java:

  1. string.length(): The length() method is a method which is applicable for string objects. length() method returns the number of characters presents in the string. The length() method is applicable for string objects but not for arrays.

    Examples:

    int length = String.length();
    
    // length() can be used
    // for String, StringBuilder, etc 
    // String class related Objects 
    // to know the length of the String
    

    Below is the illustration of how to get the length of String in Java using length() method:



    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program to illustrate
    // how to get the length of String
    // in Java using length() method
      
    public class Test {
        public static void main(String[] args)
        {
            // Here str is a string object
            String str = "GeeksforGeeks";
      
            System.out.println(
                "The size of "
                + "the String is "
                + str.length());
        }
    }

    chevron_right

    
    

    Output:

    The size of the String is 13
    
  2. String[].length: length is a final variable applicable for arrays. With the help of length variable, we can obtain the size of the array.

    Examples:

    int size = String[].length;
    
    // length can be used for String[]
    // to know the length of the array.
    

    Below is the illustration of how to get the length of String[] in Java using length variable:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program to illustrate
    // how to get the length of String[]
    // in Java using length variable
      
    public class Test {
        public static void main(String[] args)
        {
            // Here str is the array name of String type.
            String[] str = { "GEEKS", "FOR", "GEEKS" };
      
            System.out.println(str.length);
        }
    }

    chevron_right

    
    

    Output:

    3
    


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.