Java String length() Method Example

1. Introduction

The String.length() method in Java is used to get the length of a string, which is the number of characters it contains. This method is essential for many operations in Java that involve string manipulation, such as loops, conditional checks, and processing text. This tutorial will demonstrate how to use the length() method with an example.

Key Points

- length() returns the number of characters in a string.

- The method returns an int value.

- This method is one of the most commonly used in Java for string operations.

2. Program Steps

1. Declare a string.

2. Get the length of the string using length().

3. Print the length.

3. Code Program

public class StringLengthExample {
    public static void main(String[] args) {
        // Declare a String
        String str = "Hello, Java!";
        // Get the length of the string
        int length = str.length();
        // Print the length of the string
        System.out.println("Length of the string: " + length);
    }
}

Output:

Length of the string: 12

Explanation:

1. String str = "Hello, Java!": Declares and initializes a String variable str.

2. int length = str.length(): Calls the length() method on str to calculate the number of characters in the string.

3. System.out.println("Length of the string: " + length): Prints the length of the string to the console.


Comments