The length() method in Java is used to determine the number of characters in a String. It returns the total count of characters, including spaces, special characters, and digits.
Syntax:
java
int length = string.length();
Parameters:
– The length() method does not take any parameters.
Return Value:
– Returns an integer representing the number of characters in the String.
Examples:
Example 1:
Basic Usage
java
public class Main {
public static void main(String[] args) {
String str = “Hello, World!”;
System.out.println(“The length of the string is: ” + str.length());
}
}
Output:
The length of the string is: 13
Example 2:
Length of an Empty String
java
public class Main {
public static void main(String[] args) {
String str = “”;
System.out.println(“The length of the string is: ” + str.length());
}
}
Output:
The length of the string is: 0
Example 3:
Length with Spaces
java
public class Main {
public static void main(String[] args) {
String str = ” Java Programming “;
System.out.println(“The length of the string is: ” + str.length());
}
}
Output:
The length of the string is: 23
Example 4:
Using length() with Special Characters
java
public class Main {
public static void main(String[] args) {
String str = “Hello@2025#”;
System.out.println(“The length of the string is: ” + str.length());
}
}
Output:
The length of the string is: 11
Example 5: Checking String Length in a Loop
java
public class Main {
public static void main(String[] args) {
String[] strings = { “Java”, “Python”, “C++”, “” };
for (String str : strings) {
System.out.println(“The length of \”” + str + “\” is: ” + str.length());
}
}
}
Output:
The length of “Java” is: 4
The length of “Python” is: 6
The length of “C++” is: 3
The length of “” is: 0
Key Notes:
1. The length() method does not count surrogate pairs as a single character.
2. It is different from the array’s .length property and the StringBuilder’s .length() method, but they all provide similar functionality for their respective data types