In Java, length() returns how many char values a string contains. "Hello".length() is 5, and the empty string "" has length 0. Spaces, tabs, and punctuation all count.
The valid indexes of a string run from 0 to length() - 1, so length() appears in almost every loop, bounds check, and validation rule. Note the parentheses: arrays use the field array.length, strings use the method text.length().
length() is an instance method of java.lang.String, available since JDK 1.0. Call it on a string, as in text.length(); calling it on a null reference throws NullPointerException. It only reads the text; the string itself is never changed.
Syntax
Call it with no arguments; the result is an int.
java
int size = text.length();
char last = text.charAt(text.length() - 1);
boolean tooLong = name.length() > 20;
Call
What it does
"Java".length()
4.
"".length()
0.
"a b".length()
3: the space counts.
length() counts UTF-16 code units. Most characters are one unit, but emoji and other characters above U+FFFF are two. Use codePointCount(0, length()) to count Unicode code points instead.
Library declarations
java
public int length();
Parameters
Parameter
Description
None
length() takes no parameters.
Return Value
Return Value
Description
int
The number of chars in the string (0 or more).
Java Examples
Example 1 — Count the Characters of Different Strings
Spaces, tabs, and the empty string all follow the same rule.
java
public class LengthBasics {
public static void main(String[] args) {
System.out.println("Hello".length());
System.out.println("".length());
System.out.println("Hi there".length());
System.out.println("Tab\tEnd".length());
}
}
Output
5
0
8
7
How It Works
Letters only."Hello" has five chars, and the empty string has none.
Whitespace is a char too."Hi there" counts its space: 2 + 1 + 5 = 8.
An escape is one char.\t is written with two symbols in the source but stores a single tab char, so "Tab\tEnd" has length 7.
Example 2 — Check a Minimum Password Length
Reject passwords shorter than eight characters and report their length.
java
public class LengthPassword {
public static void main(String[] args) {
String[] passwords = {"secret", "correct horse", "12345678"};
int min = 8;
for (String p : passwords) {
String verdict = p.length() >= min ? "ok" : "too short (" + p.length() + ")";
System.out.println(p + " -> " + verdict);
}
}
}
Output
secret -> too short (6)
correct horse -> ok
12345678 -> ok
How It Works
Compare with a limit.p.length() >= min is the whole rule; min is 8.
Short input."secret" has 6 chars and fails, and the message includes the measured length.
Exactly the limit passes."correct horse" (13) and "12345678" (8) are both accepted.
Example 3 — Why an Emoji Has Length 2
Compare an accented word with a single smiley and count its code points.