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
| Parameter | Type | Description |
|---|---|---|
| beginIndex | int | The index of the first character included in the result. |
| endIndex | int | The 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
worldTogether 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.comNotes
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
- String.indexOf() — Finds the position of the first occurrence of a character or a substring.
- String.charAt() — Returns the character at the given index.
- String.length() — Returns the number of characters in a string.
- String.split() — Splits a string into an array of parts by a separator.
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.