Java String.subSequence
Return part of a string through the CharSequence interface.
A simple example
String.subSequence
- Start with "abc"
- Do this Take the first two characters
- Result "ab"
class Main {
public static void main(String[] args) throws Exception {
System.out.println("abc".subSequence(0, 2));
}
}
ab
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.javaPass 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.
class Main {
public static void main(String[] args) throws Exception {
String code = "ENG-101";
CharSequence subject = code.subSequence(0, 3);
System.out.println(subject);
}
}
ENG
The receiving API can use the three-character subject through its CharSequence interface.
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.
class Main {
public static void main(String[] args) throws Exception {
String shelf = "B-042";
System.out.println(shelf.subSequence(2, 5).length());
}
}
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?
What to watch for
This uses the same UTF-16 bounds as substring. The declared return type is CharSequence.