Java Reference ยท java.lang
Java String.length() method
Reference for Java String.length(): the number of UTF-16 code units in a string, why emoji count as two, and how to count real characters.
String.length() returns the number of UTF-16 code units (char values) in a string. For plain English text that equals the number of characters. For text with emoji or rare scripts it does not, because those characters are stored as two code units, called a surrogate pair.
The method runs in constant time. Note the parentheses: arrays use the field array.length, strings use the method s.length(), and collections use size().
int n = "hello".length(); // 5
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public int length()
Returns: the number of char values (UTF-16 code units) in the string. The result is never negative; an empty string gives 0.
Throws: nothing, but calling it on a null reference throws NullPointerException.
Usage notes
- Code units, not characters.
"๐".length()is2. UsecodePointCount(0, s.length())ors.codePoints().count()when you need the number of Unicode code points. - User-perceived characters (grapheme clusters, such as a letter plus a combining accent or a family emoji) can be several code points. Use
java.text.BreakIteratorto count those. - Valid indexes for
charAt()andsubstring()run from0tolength() - 1(andlength()itself as an end index). isEmpty()is the clearer way to checklength() == 0; isBlank() also treats whitespace-only strings as empty.- Not the byte count. The size in bytes depends on the encoding:
s.getBytes(StandardCharsets.UTF_8).length. - Other types.
StringBuilder.length()andCharSequence.length()behave the same way; arrays use thelengthfield; collections usesize(). - Performance. O(1). Hoisting
s.length()out of a loop condition gains nothing measurable.