The Java String length() method returns the length of a string. On this page, we are going to share a few examples through which you will understand the working of the length() method.

Java String length():

Method signature:

The signature for a length() method is as shown below.

public int length()

Method parameters and return type:

Return type: It returns a total number of characters in a String.

Parameters: It doesn’t take any parameters.

Throws: It throws NullPointerException if the string is null.

Example 1:

Here we are simply finding the length of a string by using this method.

Source code:

public class Example1 {
    
    public static void main(String[] args) {
        
        String str = "It is a Java Length method tutorial";
        int length= str.length();
        System.out.println(length);
    }
}

Output:

run:
35
BUILD SUCCESSFUL (total time: 4 seconds)

Example 2:

In this example, we are comparing the lengths of two strings variables with different values.

Source code:

public class Example2 {
    
    public static void main(String[] args) {
        String str1 = "Java Programmers";
        String str2 = "Python Programmer";
        
        if(str1.length() == str2.length()){
            System.out.println("Length of strings is equal");
        } else {
            System.out.println("Length of strings is not equal");
        }
    }
}

Output:

run:
Length of strings is not equal
BUILD SUCCESSFUL (total time: 0 seconds)

Example 3:

The length() method can also be used in a loop for iterating till the length of the string. Here is an example that explains this concept.

Source code:

public class Example3 {
    
    public static void main(String[] args) {
        
        String str = "Converting into character array";
        
        char charArray[] = new char[str.length()];
        
        for(int i=0; i<str.length(); i++){
            charArray[i] = str.charAt(i);
        }
        System.out.println(charArray);
    }
}

Output:

run:
Converting into character array
BUILD SUCCESSFUL (total time: 0 seconds)

References:

Happy Learning 🙂

Leave A Comment