Library contents

Java String.length

Count the units in a plain ASCII parcel code before checking its expected length.

A simple example

String.length

  1. Start with "abc"
  2. Do this Count the characters
  3. Result 3
Count a, then b, then c. These simple ASCII characters each count as one here.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("abc".length());
    }
}
Output
3

Syntax

Java 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.java

Check 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.

From the programString label = "PK-407"
Result6
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        String label = "PK-407";
        System.out.println(label.length());
    }
}
Output
6

The two letters, hyphen, and three digits make six units.

Advertisements

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.

From the programString room = "LAB-204"
Result7
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String room = "LAB-204";
        System.out.println(room.length());
    }
}
Output
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.

From the programString ticket = "A🎫"
Result3
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String ticket = "A🎫";
        System.out.println(ticket.length());
    }
}
Output
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.

Documentation for String.length