length()

Returns the number of UTF-16 code units in a String, which is not always the number of characters a person sees.

Signature
public int length()
  • Added in Java Java 1.0

Return value

intThe number of char values (UTF-16 code units) in the string. An empty string returns 0.

Errors

Nothing. Calling it on a null reference throws NullPointerException.

length() tells you how many char values a String holds. Every index-based method on String, such as charAt, substring and indexOf, works in the same unit, so valid indexes always run from 0 to length() - 1.

A char is a UTF-16 code unit, not a character

Java stores text as UTF-16. Most characters you meet in English text, accented Latin letters and most CJK characters fit in one char. Emoji and other characters outside the Basic Multilingual Plane need two, called a surrogate pair. So "\uD83D\uDE00".length() is 2 even though it is one smiley.

Accents add a second trap. "caf\u00e9" uses one precomposed é and has length 4; "cafe\u0301" uses e plus a combining accent and has length 5. They look identical on screen. If that matters, normalise with java.text.Normalizer before you measure.

Which count do you want?

  • char count: length(). Right for index loops and for any limit defined in Java chars.
  • Code points: codePointCount(0, length()). Closer to what a user thinks of as characters, and the safer choice for a visible limit such as a 280 character post. PostgreSQL also counts characters, not chars, for VARCHAR(n).
  • Bytes: getBytes(StandardCharsets.UTF_8).length. What a request body limit, a VARCHAR sized in bytes or a Kafka message limit actually counts.

Common mistakes

Arrays use a field, array.length, Strings use a method, s.length(), and collections use size(). Mixing them up is a compile error, not a runtime one. Calling length() on a null String throws NullPointerException, so check for missing input first. And measure after you strip: " ab ".length() is 6, which can let a blank-looking value pass a minimum length rule.

isEmpty() is the same as length() == 0 and reads better. To treat whitespace-only input as empty, use isBlank().

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Rejecting a username longer than the VARCHAR(20) column before the insert fails.
  • Checking that an API key header has the exact length your key format defines.
  • Looping over every index of a request path to parse it by hand.

Frequently asked questions

Why does length() return 2 for a single emoji?

length() counts UTF-16 code units. Characters outside the Basic Multilingual Plane, including most emoji, are stored as a surrogate pair of two chars. Use codePointCount(0, s.length()) to count code points instead.

Does String.length() return the number of bytes?

No. It returns the number of chars. For the size in a given encoding, call getBytes(StandardCharsets.UTF_8).length; an accented letter such as é is 1 char but 2 bytes in UTF-8.

What is the difference between length and length() in Java?

length is a field on arrays and length() is a method on String and other CharSequence types. Collections such as List use size().

More examples

Enforcing a length rule on input

The null check comes first and the length is measured after strip(), so " jo " is judged as the two letters it really is. This is the same order a request validator should use before the value reaches a database column.

Example · java
String check(String raw) {
    if (raw == null) return "missing";
    String name = raw.strip();            // measure what you will store
    if (name.isEmpty()) return "missing";
    if (name.length() < 3) return "too short";
    if (name.length() > 20) return "too long";
    return "ok";
}

void main() {
    for (String in : new String[] {"ada", "  jo  ", "a".repeat(21), "   ", "grace_hopper"}) {
        IO.println("[" + in + "] -> " + check(in));
    }
    IO.println("null -> " + check(null));
}
// Output:
// [ada] -> ok
// [  jo  ] -> too short
// [aaaaaaaaaaaaaaaaaaaaa] -> too long
// [   ] -> missing
// [grace_hopper] -> ok
// null -> missing

Truncating by code points, not chars

The two rockets add 4 to length() but only 2 to the code point count. offsetByCodePoints turns a code point count back into a char index, so substring never cuts a surrogate pair in half and leaves a broken character at the end of a preview.

Example · java
String preview(String text, int maxCodePoints) {
    if (text.codePointCount(0, text.length()) <= maxCodePoints) return text;
    int end = text.offsetByCodePoints(0, maxCodePoints);
    return text.substring(0, end) + "...";
}

void main() {
    String msg = "Deploy done \uD83D\uDE80\uD83D\uDE80 all green";
    IO.println(msg.length());
    IO.println(msg.codePointCount(0, msg.length()));
    IO.println(preview(msg, 13));
    IO.println(preview("short", 13));
}
// Output:
// 26
// 24
// Deploy done 🚀...
// short

length, length() and size()

Arrays expose a final field, while String and StringBuilder implement CharSequence.length(). Collections use size() instead, and the compiler reports any mix-up straight away.

Example · java
void main() {
    String[] parts = "a,b,c".split(",");
    String word = "hello";
    List<String> list = List.of("x", "y");
    StringBuilder sb = new StringBuilder("abc").append("de");

    IO.println(parts.length);   // array: a field, no brackets
    IO.println(word.length());  // String: a method
    IO.println(list.size());    // collection: size()
    IO.println(sb.length());    // StringBuilder: also length()
}
// Output:
// 3
// 5
// 2
// 5

Discussion

  • Be the first to comment on this lesson.