Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.length()

Returns the number of characters in a string.

Available since: Java 1.0

Syntax

public int length()

Return value

intThe length of the string in char units.

Examples

Length of a string and of an empty string:

void main() {
    IO.println("Hello".length());
    IO.println("".length());
}

Output:

5
0

The length is often used to get the last character:

void main() {
    String word = "Java";
    char last = word.charAt(word.length() - 1);
    IO.println(last);
}

Output:

a

Notes

For a string, length() is a method with parentheses. For an array, length is a field without them: array.length. Lists use size().

The length is counted in char units. Most emoji take two char values, so "😀".length() is 2. The number of real characters is text.codePointCount(0, text.length()).

See also

  • String.charAt() — Returns the character at the given index.
  • String.isEmpty() — Checks whether the string length is zero.
  • String.isBlank() — Checks whether a string is empty or contains only whitespace.
  • array.length — The length of an array — the number of elements. A field, not a method: no parentheses.

Related recipes

In the tutorial

  • Strings — The String type in Java: creating strings, joining with +, length, characters by index, escaping and comparing with equals.

Thanks for reading!

Donate to the site — we work hard for you.