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);9
tekstasstores the value JavaQuest.- The method
tekstas.length()counts this string's UTF-16 code units. - The word has nine ordinary letters, so the method returns
9. - The number is stored in
intvariableilgisand printed in the console.
Method syntax
public int length()
| Part | Meaning |
|---|---|
| Calling object | A specific String, for example, tekstas |
| Parameters | The method takes no parameters |
| Return type | int |
| Minimum result | 0when 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());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());9
10
8
- JavaQuest has nine letters.
- Java Quest has the same nine letters and one space, giving length
10. - Java has four letters and four surrounding spaces.
length()does not remove them, so the third result is8.
An empty string and a space are different
String tuscias = "";
String vienasTarpas = " ";
System.out.println(tuscias.length());
System.out.println(vienasTarpas.length());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ų");
}Vardas tinkamo ilgio
vartotojoVardasstores the text Rūta.length()returns4, and the result is stored to avoid calculating it again.- The first condition checks whether the length is at least
3. - The second checks whether it is at most
20. - 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);8
t
- JavaQuest has length
9. - Indices start at
0, so the last index islength() - 1, in this case8. charAt(8)returns the final character, t.
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());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()));4
3
- A person looking at A😀B sees three characters.
- Java
Stringuses UTF-16, and this smiley needs two code units. - Therefore,
length()countsA, the smiley's two units andB: a total of4. codePointCount()counts Unicode code points and returns3.
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());4
3
2
| Meaning | Syntax |
|---|---|
String | tekstas.length() – a method with parentheses |
| The array | skaiciai.length – a field without parentheses |
| Collection | kalbos.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());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.lengthwithout parentheses even thoughString.length()is a method. - Writing
masyvas.length()even though an array'slengthis a field without parentheses. - Using this for a collection's size:
length(), although collections havesize(). - Forgetting that spaces, newlines and punctuation also increase the length.
- Treating the last index as
length()when it islength() - 1. - Assuming every visible Unicode character occupies one UTF-16 position.
- Calling the method through a
nullreference and getting aNullPointerException.
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().