In this tutorial, you will learn about String length() method, its syntax, and usage with examples.

Java String length() method

In Java, String length() method returns the length of the string, which is the number of Unicode code points in the string, as an integer value.

Syntax of length()

The syntax to call String length() method in Java is

string.length()

length() method takes no parameters.

length() returns value of int type, representing the number of characters in the string.

ADVERTISEMENT

Examples

1. length() – Get length of string “Hello World” in Java

In this example, we take a string value in str and find its length using String length() method.

Java Program

public class Main {
	public static void main(String[] args) {
		String str = "Hello World";
		int strLength = str.length();
		System.out.println("String length : " + strLength);
	}
}

Output

String length : 11

2. Get length of an empty string

In this example, we take an empty string in str, and find its length. Since the string is empty, length() method should return 0.

Java Program

public class Main {
	public static void main(String[] args) {
		String str = "";
		int strLength = str.length();
		System.out.println("String length : " + strLength);
	}
}

Output

String length : 0

Conclusion

In this Java String Methods tutorial, we have seen about String length() method in Java, its syntax, and how to use String length() method in Java programs with the help of examples.