Library contents

Java String.subSequence

Return part of a string through the CharSequence interface.

A simple example

String.subSequence

  1. Start with "abc"
  2. Do this Take the first two characters
  3. Result "ab"
The selected region includes a and b. The third character is outside it.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("abc".subSequence(0, 2));
    }
}
Output
ab

Syntax

Java syntax
public CharSequence subSequence(int beginIndex, int endIndex)
JDK 21 method signatures (1)
public CharSequence subSequence(int beginIndex, int endIndex)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Pass a course prefix to a text API

A display component receives text through a general-purpose interface. Convert or transform the supplied value at the boundary where the component needs the final printable label.

From the programString code = "ENG-101"
ResultENG
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String code = "ENG-101";
        CharSequence subject = code.subSequence(0, 3);
        System.out.println(subject);
    }
}
Output
ENG

The receiving API can use the three-character subject through its CharSequence interface.

Advertisements

Measure the aisle portion of a shelf code

A structured code contains a department, room or other routing field inside a longer label. Extract the exact portion needed by the receiving system and verify which boundary is excluded.

From the programString shelf = "B-042"
Result3
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String shelf = "B-042";
        System.out.println(shelf.subSequence(2, 5).length());
    }
}
Output
3

The range covers positions two, three and four.

Read a parcel sorting code

The depot scans a parcel marked NC-17. The printer needs the two-letter prefix that comes before the separator. Which letters should it print?

GivenNC-17
Worked resultNC

What to watch for

This uses the same UTF-16 bounds as substring. The declared return type is CharSequence.

Documentation for String.subSequence