Java String Length: How the length() Method Really Works

How-to basics · Updated November 22, 2026

In Java, call length() on a String to get its length: for example, "Java".length() returns 4. The result counts UTF-16 code units, not necessarily the number of visible characters, so some Unicode text has a length that may surprise you.

The String length() Method

length() is a public method of Java’s String class. It returns an int representing how many UTF-16 code units the string contains. A code unit is the basic 16-bit unit used by Java’s char type and UTF-16 encoding. For ordinary English text, each letter, digit, space, or punctuation mark takes one code unit, which makes the returned value look like a simple character count.

Here is a small example:

String language = "Java";
int size = language.length();
System.out.println(size); // 4

The method belongs to the string object, so the parentheses matter: use language.length(), not language.length. The latter syntax is used for an array’s length field, not for a String method. Java strings are immutable, meaning their contents cannot be changed after creation; if you create a different string, that new string has its own length.

Basic Examples and Empty Strings

Spaces and punctuation count just like letters. For example, "Hi, Java!".length() returns 9: two letters, a comma, a space, four letters, and an exclamation mark. A space is a character in the string, even though it may be easy to overlook when inspecting output.

An empty string has length zero, while a string containing a space does not:

System.out.println("".length());  // 0
System.out.println(" ".length()); // 1

These distinctions are useful when validating input. A check such as text.length() == 0 finds an empty string, but it does not reject a string made only of spaces. If the requirement is to reject blank or whitespace-only input, use a suitable whitespace check as well; in Java 11 and later, String.isBlank() checks whether a string is empty or contains only whitespace code points.

For a variable, call the method on that variable:

String username = "mira42";
if (username.length() < 6) {
    System.out.println("Use at least six UTF-16 code units.");
}

The example’s threshold is deliberately described in code units. If a program’s rule is about visible characters or a particular encoding’s byte limit, a plain length check may not express the intended rule.

Why Unicode Can Change the Result

Java’s char represents one UTF-16 code unit, not every possible Unicode character by itself. Unicode values above U+FFFF are represented in UTF-16 by a pair of code units called a surrogate pair. Consequently, one symbol that a reader sees as a single character can contribute two to String.length().

For example, the smiling face U+1F600 can be written in Java source as "\uD83D\uDE00", using its two UTF-16 surrogate units. The string "A\uD83D\uDE00B" has a length of 4: one unit for A, two for the emoji, and one for B. It contains three Unicode code points, however. This is expected behavior, not a bug in length().

Some visually combined text uses multiple Unicode code points even when none requires a surrogate pair. For instance, an accented letter may be represented as a base letter followed by a combining accent. The sequence "e\u0301" has a length of 2 and two code points, although it is commonly displayed as one accented letter. Unicode permits multiple representations of text that can look alike.

Counting Unicode Code Points Instead

If the goal is to count Unicode code points rather than UTF-16 units, use codePointCount. It takes a start index and an end index measured in UTF-16 units. To count all code points in a string, pass zero and the string’s length:

String text = "A\uD83D\uDE00B";
int points = text.codePointCount(0, text.length());
System.out.println(points); // 3

The end index is exclusive, as with many Java range methods. For this string, the valid full range runs from index zero up to, but not including, index four. codePointCount returns an int, while a stream produced by text.codePoints() can be counted with count(), which returns a long.

Code points answer a different question from UTF-16 length, but they still do not always equal the number of characters a person perceives. A base letter and combining mark are two code points, and some emoji sequences combine several code points into one displayed symbol. Choose the counting unit that matches the requirement rather than assuming one method represents every meaning of “character.”

Visible Characters, Input Limits, and Validation

When a product requirement says “maximum 20 characters,” clarify what that means. It could mean 20 UTF-16 code units, 20 Unicode code points, 20 grapheme clusters (roughly, user-perceived characters), or a maximum number of bytes in a file or network encoding. These limits differ for some text. A database column or external protocol may impose a byte limit that cannot be checked correctly with String.length() alone.

  • Java indexing or a limit defined in char units: length() is the relevant count.
  • Unicode code point count: use codePointCount(0, text.length()).
  • Encoded byte size: encode with the required charset and inspect the resulting byte array’s length.
  • User-perceived characters: use grapheme-cluster-aware text segmentation appropriate to the application and its Unicode requirements.

For example, UTF-8 byte size depends on the characters and the chosen encoding. A basic Latin letter commonly occupies one UTF-8 byte, while many other code points occupy more. To measure bytes for a defined format, specify the charset explicitly rather than relying on a platform default. Also consider normalization if a system requires equivalent-looking text to have a consistent representation; normalization can change the sequence of code points and therefore its counts.

String, Array, and StringBuilder Lengths

Java uses similar terminology across types, but the syntax differs. A string uses the method text.length(). An array has a public field named length, so an array uses items.length. Do not add parentheses to the array field.

String text = "Java";
int stringSize = text.length();

int[] values = {10, 20, 30};
int arraySize = values.length;

For a StringBuilder, call builder.length(). It reports the number of UTF-16 code units currently in the builder’s contents. Its capacity() method reports how much storage is available before the builder needs to grow; capacity is not the current text length. For example, a builder can have a capacity of 16 while holding only three characters. Confusing those two numbers can lead to incorrect assumptions about the text being processed.

Null Values and Other Common Mistakes

A variable that refers to null does not refer to a string object, so calling length() on it throws a NullPointerException. The length of a string is never “null”; rather, the variable may be null. Check it before calling the method when null is a permitted state:

if (text != null && text.length() > 0) {
    System.out.println("The string is not empty.");
}

Java evaluates the right side of && only if the left side is true, so this guard prevents the method call when text is null. Alternatively, define a clear policy for missing values where the string is created or received. Silently treating null as an empty string can hide a data problem if the two states have different meanings in the application.

  • Do not write text.length for a string; use text.length().
  • Do not assume length counts visible glyphs, bytes, or Unicode code points in every case.
  • Do not call the method before considering whether the reference can be null.
  • Do not confuse StringBuilder.capacity() with the builder’s current length().

Performance and Practical Use

Calling length() is the normal way to ask a string for its size, and it is suitable for conditions, loops, and validation. Java’s public API specifies the returned count, not a particular internal storage layout or a formal time-complexity guarantee. In ordinary Java implementations, the string keeps information that makes retrieving its length inexpensive; application code should rely on the API contract, not on assumptions about how a particular JVM stores strings internally.

In a loop, storing the length in a local variable can sometimes make the intent clearer, especially if the expression is long. For an immutable String, the value does not change while that same object is being used. With a mutable StringBuilder, its length can change as you append or delete text, so decide whether a loop should use the current length or a snapshot. Correctness and clear bounds matter more than trying to optimize a simple method call without evidence of a performance problem.

Frequently Asked Questions

What does String.length() return in Java?
It returns an int counting the string’s UTF-16 code units. For basic English text this usually matches the number of characters, but supplementary Unicode characters can use two units.

Is the length of a Java string the same as its character count?
Not always. It is a count of UTF-16 code units. Code points can be counted with codePointCount(0, text.length()), while user-perceived characters may require grapheme-aware segmentation.

How do I get the length of a string array?
Use array.length, without parentheses, to get the number of elements in the array. For one string stored in an array, use an expression such as array[0].length(), after ensuring the element is not null.

What does "".length() return?
It returns 0, because the empty string contains no UTF-16 code units. A string containing one space has length 1.

Can calling length() cause a NullPointerException?
Yes. If the variable is null, there is no string object on which to call the method. Check text != null before calling text.length() when null is possible.

How is StringBuilder.length() different from capacity()?
length() is the number of code units currently in the builder’s text. capacity() is the amount of storage available before it needs to expand; it can be larger than the current length.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.