Java String.substring
Use substring to copy a portion of a string. The first index is included and the ending index is excluded.
A simple example
String.substring
- 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".substring(0, 2));
}
}
ab
Syntax
text.substring(start, end)
JDK 21 method signatures (2)
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRead the part before a dash
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.
public class Main {
public static void main(String[] args) throws Exception {
for (String receipt : new String[]{"NTH-204", "204"}) {
int dash = receipt.indexOf('-');
System.out.println(dash > 0 ? receipt.substring(0, dash) : "No shop code");
}
}
}
NTH No shop code
The dash in NTH-204 is at index 3. The range from 0 up to 3 contains NTH. The second receipt has no dash, so the example takes the fallback branch.
Read the department on a roster
A roster entry starts with a department identifier followed by other student details. Extract just the department so the admissions desk can route the record to the right office.
class Main {
public static void main(String[] args) throws Exception {
String course = "BIO-204";
System.out.println(course.substring(0, 3));
}
}
BIO
The first three positions form the department code.
Extract the last digits of a ticket
A scanner returns a compound code, but the printed field needs only its numeric or trailing portion. Use the input boundaries and destination capacity to copy the intended range without including the prefix.
class Main {
public static void main(String[] args) throws Exception {
String ticket = "TRAIN-725";
System.out.println(ticket.substring(ticket.lastIndexOf('-') + 1));
}
}
725
Starting just after the hyphen keeps the entire remaining suffix.
What to watch for
Indices count UTF-16 code units. Check the position of a separator before using it as an index.