Java-Get Length

Get Length

The String class defines a number of methods that allow us to accomplish a variety of string manipulation tasks. The number of characters in a string provided by the length( ) method of the String class. Since it is an instantiated method, we have to invoke it from an object of the String class.

Here is an interesting observation. Since an object instance is created for every string literal in Java, we can call the length( ) method on the String literal “JavaProgram” itself directly, as if it is an object reference. For example, in the following program, the length of the string “JavaProgram” will be displayed as the output.

Program

final2

Program Source

public class Javaapp {

    public static void main(String[] args) {
       
        String str = new String("JavaProgram");

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

Leave a Comment