Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.substring()

Returns the part of a string between two indexes.

Available since: Java 1.0

Syntax

public String substring(int beginIndex, int endIndex)

Parameters

ParameterTypeDescription
beginIndexintThe index of the first character included in the result.
endIndexintThe index where the part ends; that character is not included. Can be omitted to take the rest of the string.

Return value

StringA new string.

Examples

With two indexes and with one:

void main() {
    String text = "Hello, world";
    IO.println(text.substring(0, 5));
    IO.println(text.substring(7));
}

Output:

Hello
world

Together with indexOf() — everything after the @ sign:

void main() {
    String email = "anna@example.com";
    String domain = email.substring(email.indexOf('@') + 1);
    IO.println(domain);
}

Output:

example.com

Notes

The second index is excluded: substring(0, 5) returns characters 0–4, exactly 5 of them. The result length is always endIndex - beginIndex.

If an index is negative, greater than the length, or beginIndex > endIndex, the method throws StringIndexOutOfBoundsException. The original string does not change: strings in Java are immutable.

See also

Related recipes

In the tutorial

  • String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.

Thanks for reading!

Donate to the site — we work hard for you.