Library contents

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

  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".substring(0, 2));
    }
}
Output
ab

Syntax

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

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

First output lineNTH
Main.java
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");
        }
    }
}
Output
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.

Advertisements

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.

From the programString course = "BIO-204"
ResultBIO
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String course = "BIO-204";
        System.out.println(course.substring(0, 3));
    }
}
Output
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.

From the programString ticket = "TRAIN-725"
Result725
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String ticket = "TRAIN-725";
        System.out.println(ticket.substring(ticket.lastIndexOf('-') + 1));
    }
}
Output
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.

Documentation for String.substring