Java Tutorial Java Advanced Java References

Java String - length() Method



The Java length() method is used to find out the total number of characters in the string. The length is equal to the number of Unicode code units in the string.

Syntax

public int length()

Parameters

No parameter is required.

Return Value

Returns the total number of characters in the specified string.

Exception

NA.

Example:

In the example below, length() method is used to find out the total number of characters in the string called MyString.

public class MyClass {
  public static void main(String[] args) {
    String MyString = "Hello World!.";
    System.out.println(MyString.length()); 

    MyString = "@#^%";
    System.out.println(MyString.length()); 

    MyString = "";
    System.out.println(MyString.length()); 
  }
}

The output of the above code will be:

13
4
0

❮ Java String Methods