Skip to content
Related Articles

Related Articles

How to determine length or size of a String in Java?
  • Difficulty Level : Basic
  • Last Updated : 30 Sep, 2019
GeeksforGeeks - Summer Carnival Banner

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:




    // 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());
        }
    }
    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:




    // 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);
        }
    }
    Output:
    3
    

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :