Java String length() Method

The length() method in Java returns the number of characters present in a String object. This includes all characters (letters, numbers, spaces, punctuation, etc.), but does not count the null terminator as Java strings are not null-terminated like in some other languages (e.g., C/C++). The index of the string starts at 0, but the length() method returns a count of characters, not the index.

Syntax:


int length()

Return Type:

The method returns an int representing the number of characters in the string.

Example:


public class StringLengthExample {
    public static void main(String[] args) {
        // Create a string
        String str = "Hello, World!";
        
        // Using length() to get the number of characters in the string
        int length = str.length();
        
        // Print the length
        System.out.println("The length of the string is: " + length);  // Output: 13
    }
}

Explanation:

  1. The string “Hello, World!” consists of 13 characters, including the comma and space.
  2. The length() method returns 13, which is the total number of characters in the string.

If the string is empty

If the string is empty (i.e., it contains no characters), the length() method will return 0.


public class EmptyStringExample {
    public static void main(String[] args) {
        // Create an empty string
        String emptyStr = "";
        
        // Using length() to get the number of characters in the empty string
        int length = emptyStr.length();
        
        // Print the length
        System.out.println("The length of the empty string is: " + length);  // Output: 0
    }
}

Explanation:

The empty string “” has no characters, so length() returns 0.