Java String.length
Count the units in a plain ASCII parcel code before checking its expected length.
A simple example
String.length
- Start with "abc"
- Do this Count the characters
- Result 3
class Main {
public static void main(String[] args) throws Exception {
System.out.println("abc".length());
}
}
3
Syntax
label.length()
JDK 21 method signatures (1)
public int length()Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCheck the length of a parcel code
A warehouse label uses a compact parcel identifier containing punctuation. Count the stored units across the entire identifier before testing it against the importer's length requirement.
class Main {
public static void main(String[] args) throws Exception {
String label = "PK-407";
System.out.println(label.length());
}
}
6
The two letters, hyphen, and three digits make six units.
Measure a classroom code
A registration service checks the length of a short identifier before accepting it. Include every stored unit in the count and consider what the validation sees when no characters were supplied.
class Main {
public static void main(String[] args) throws Exception {
String room = "LAB-204";
System.out.println(room.length());
}
}
7
Letters, digits and the hyphen each use one UTF-16 unit.
Count the storage units of a ticket symbol
A ticket includes a symbol outside the basic multilingual plane. Inspect its UTF-16 representation before using the string length as a count of what a reader sees on the screen.
class Main {
public static void main(String[] args) throws Exception {
String ticket = "A🎫";
System.out.println(ticket.length());
}
}
3
The letter uses one unit and the ticket emoji uses a surrogate pair.
What to watch for
Byte counts, UTF-16 code units, Unicode code points, and displayed characters can differ outside ASCII.