Skip to content
Tutorials Center
My learning

Topics

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().

Java
int n = "hello".length();   // 5

Try it

Java Length of different strings

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.

Java Using length() in loops and checks

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

Java
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() is 2. Use codePointCount(0, s.length()) or s.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.BreakIterator to count those.
  • Valid indexes for charAt() and substring() run from 0 to length() - 1 (and length() itself as an end index).
  • isEmpty() is the clearer way to check length() == 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() and CharSequence.length() behave the same way; arrays use the length field; collections use size().
  • Performance. O(1). Hoisting s.length() out of a loop condition gains nothing measurable.