Java String length() example

In this guide, you will learn about the String length() method in Java programming and how to use it with an example.

1. String length() Method Overview

Definition:

The length() method of Java's String class returns the number of characters (including whitespace) in the specified string.

Syntax:

str.length()

Parameters:

- This method doesn't accept any parameters.

Key Points:

- It returns the count of Unicode characters in the string.

- Useful for validating string input lengths, looping through characters of a string, and various other operations where you need to know the length of a string.

- Different from the size() method used in Java Collections and the length property of arrays.

2. String length() Method Example

public class LengthExample {
    public static void main(String[] args) {
        String str1 = "Java";
        String str2 = "Java Programming";
        String str3 = "";

        // Checking the length of a string
        int len1 = str1.length();
        System.out.println("Length of str1: " + len1);

        // Checking the length of a string with spaces
        int len2 = str2.length();
        System.out.println("Length of str2: " + len2);

        // Checking the length of an empty string
        int len3 = str3.length();
        System.out.println("Length of str3: " + len3);
    }
}

Output:

Length of str1: 4
Length of str2: 16
Length of str3: 0

Explanation:

In the example:

1. We begin by checking the length of the string "Java". The length() method returns 4 as there are four characters in the string.

2. Next, we assess the length of "Java Programming", which includes spaces. The method counts each character, including whitespace, and returns 16.

3. Lastly, we check the length of an empty string. As there are no characters in the string, the method returns 0.

Related Java String Class method examples

Comments