STRING INSTANCE METHODS

Java String length() method

length() returns a specific String object's length as an int value. For simple text, this is its character count, including spaces and punctuation.

Finding text length

String tekstas = "JavaQuest";

int ilgis = tekstas.length();

System.out.println(ilgis);
Console output

9

  1. tekstas stores the value JavaQuest.
  2. The method tekstas.length() counts this string's UTF-16 code units.
  3. The word has nine ordinary letters, so the method returns 9.
  4. The number is stored in int variable ilgis and printed in the console.

Method syntax

public int length()

Parts of the length() method
PartMeaning
Calling objectA specific String, for example, tekstas
ParametersThe method takes no parameters
Return typeint
Minimum result0when the string is empty
What is counted?UTF-16 code units

length() does not change text. It only reads and returns the existing String length.

Why is length() an instance method?

Length depends on the specific text, so length() is called on the selected String object:

int ilgis = miestas.length();

String miestas = "Vilnius";

System.out.println(miestas.length());
Console output

7

On the left, miestas identifies the text to measure. We therefore do not write String.length() : a static call would have no specific text value.

Spaces count too

String beTarpo = "JavaQuest";
String suTarpu = "Java Quest";
String suKrastiniaisTarpais = "  Java  ";

System.out.println(beTarpo.length());
System.out.println(suTarpu.length());
System.out.println(suKrastiniaisTarpais.length());
Console output

9
10
8

  1. JavaQuest has nine letters.
  2. Java Quest has the same nine letters and one space, giving length 10.
  3. Java has four letters and four surrounding spaces.
  4. length() does not remove them, so the third result is 8.

An empty string and a space are different

String tuscias = "";
String vienasTarpas = " ";

System.out.println(tuscias.length());
System.out.println(vienasTarpas.length());
Console output

0
1

The empty string "" has no characters, so its length is 0. The string " " contains one space, so its length is 1. For an emptiness check alone, write tekstas.isEmpty().

Practical example: checking input length

String vartotojoVardas = "Rūta";
int ilgis = vartotojoVardas.length();

if (ilgis >= 3 && ilgis <= 20) {
  System.out.println("Vardas tinkamo ilgio");
} else {
  System.out.println("Vardas turi turėti nuo 3 iki 20 simbolių");
}
Console output

Vardas tinkamo ilgio

  1. vartotojoVardas stores the text Rūta.
  2. length() returns 4, and the result is stored to avoid calculating it again.
  3. The first condition checks whether the length is at least 3.
  4. The second checks whether it is at most 20.
  5. Both are true, so a success message is printed.

Length and the last index

String tekstas = "JavaQuest";
int paskutinisIndeksas = tekstas.length() - 1;

char paskutinisSimbolis = tekstas.charAt(paskutinisIndeksas);

System.out.println(paskutinisIndeksas);
System.out.println(paskutinisSimbolis);
Console output

8
t

  1. JavaQuest has length 9.
  2. Indices start at 0, so the last index is length() - 1, in this case 8.
  3. charAt(8) returns the final character, t.
Important

Before using length() - 1, ensure the string is not empty. An empty string would produce index -1, while charAt(-1) would cause an error.

Length before and after removing whitespace

String ivestis = "  Java  ";

System.out.println(ivestis.length());
System.out.println(ivestis.strip().length());
Console output

8
4

The first call also counts the four surrounding spaces. strip() returns a new string without leading or trailing whitespace, so the following length() returns only the word's Java length.

A Unicode character may occupy more than one position

String tekstas = "A😀B";

System.out.println(tekstas.length());
System.out.println(tekstas.codePointCount(0, tekstas.length()));
Console output

4
3

  1. A person looking at A😀B sees three characters.
  2. Java String uses UTF-16, and this smiley needs two code units.
  3. Therefore, length() counts A, the smiley's two units and B : a total of 4.
  4. codePointCount() counts Unicode code points and returns 3.

More complex visible characters may consist of several code points, so neither length()nor codePointCount() always equals the number of characters visible on screen.

Strings, arrays and collections use different size operations

String tekstas = "Java";
int[] skaiciai = {10, 20, 30};
List<String> kalbos = List.of("Java", "Python");

System.out.println(tekstas.length());
System.out.println(skaiciai.length);
System.out.println(kalbos.size());
Console output

4
3
2

Obtaining the size of different Java values
MeaningSyntax
Stringtekstas.length() – a method with parentheses
The arrayskaiciai.length – a field without parentheses
Collectionkalbos.size() – a method

The example uses List, so a complete class needs an import of java.util.List or java.util.*.

The method cannot be called on null

String tekstas = null;

System.out.println(tekstas.length());
Result

NullPointerException

null means that String object does not exist, so there is no text whose length can be read. If the variable might be null, first check tekstas != null.

Common mistakes

  • Writing tekstas.length without parentheses even though String.length() is a method.
  • Writing masyvas.length()even though an array's length is a field without parentheses.
  • Using this for a collection's size: length(), although collections have size().
  • Forgetting that spaces, newlines and punctuation also increase the length.
  • Treating the last index as length()when it is length() - 1.
  • Assuming every visible Unicode character occupies one UTF-16 position.
  • Calling the method through a null reference and getting a NullPointerException.

When should you use length()?

Use length()to validate input limits, find the last valid index, control a loop, compare string lengths or check for any characters. For emptiness alone, it is often clearer to use isEmpty(); to include whitespace-only text, use isBlank().