The substring() method in Java is used to extract a portion (sub-string) of a string. It belongs to the String class and allows you to create a new string by selecting a part of an existing string.
Parameters in Method
1. String substring(int beginIndex)
This method returns a new string that starts from the specified beginIndex to the end of the string.
Example:
public class SubstringSingleParameterExample {
public static void main(String[] args) {
String str = "Hello, World!";
// Extract substring from index 7 to the end of the string
String subStr1 = str.substring(7);
System.out.println(subStr1); // Output: World!
}
}
Explanation: substring(7) starts at index 7 and returns the substring from there to the end of the string: “World!”
2. substring(int beginIndex, int endIndex)
The method returns a new String object that contains the characters from the original string, starting from the beginIndex (inclusive) and optionally up to endIndex (exclusive).
Example:
public class SubstringTwoParametersExample {
public static void main(String[] args) {
String str = "Hello, World!";
// Extract substring from index 0 to index 5 (exclusive)
String subStr2 = str.substring(0, 5);
System.out.println(subStr2); // Output: Hello
}
}
Explanation: In this example, substring(0, 5) extracts the substring starting at index 0 and ending at index 4, which gives the substring “Hello”.
3. Handle Invalid Index
public class SubstringExample {
public static void main(String[] args) {
String str = "Hello World!";
try {
String subStr = str.substring(15, 5);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage()); // Output: String index out of range: 15 to 5
}
}
}
Explanation: Here, attempting to extract a substring where the beginIndex (15) is greater than endIndex (5) throws a StringIndexOutOfBoundsException.