Java 25 (LTS) reference · String Methods

Java String substring() Method

Return part of a string from a start index up to (not including) an end index. The original is unchanged.

Java 25 (LTS) Since Java 1.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

string.substring(beginIndex, endIndex)

Parameters

ParameterDescription
beginIndex
int
First index to include.
endIndex optional
int
Index to stop before. Default: length()

Return value

A new String.

Examples

Split an email address
public class Main {
    public static void main(String[] args) {
        String email = "[email protected]";
        int at = email.indexOf("@");
        System.out.println(email.substring(0, at));
        System.out.println(email.substring(at + 1));
    }
}

Output

ana
example.com

Run this on your computer — see “Get Started” for setup.

Truncate long text
public class Main {
    public static void main(String[] args) {
        String title = "Interview Questions";
        String shortTitle = title.length() > 9 ? title.substring(0, 9) + "…" : title;
        System.out.println(shortTitle);
    }
}

Output

Interview…

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 1.0Added

Was this page helpful?