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
Syntax
string.substring(beginIndex, endIndex)
Parameters
| Parameter | Description |
|---|---|
beginIndexint |
First index to include. |
endIndex optionalint |
Index to stop before. Default: length() |
Return value
A new String.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
string.indexOf()· Return the index of the first occurrence of a character or substring, or -1 if it isn't found.string.split()· Split a string around matches of a regular expression and return the parts as an array.- Java Strings · tutorial