The substring() method of the StringBuilder class is used to extract a portion of characters from an existing character sequence and return it as a new String. It always returns a new String object and does not modify the original StringBuilder. Indexing is zero-based, and passing invalid index values results in runtime exceptions.
Example.
class GFG {
public static void main(String[] args)
{
StringBuilder str= new StringBuilder("GeeksForGeeks"); // string
System.out.println("Substring = "+ str.substring(5));
}
}
Output
Substring = ForGeeks
Explanation: Index 5 points to the character 'F'. All characters from index 5 to the end are returned as a new String.
Syntax
public String substring(int start, int end)
Parameter:
- start: starting index (inclusive)
- end (optional): ending index (exclusive)
Return Type: String
Example 1. Extracting a Substring Starting from a Specific Index
class GFG {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("GeeksForGeeks");
System.out.println("Substring = " + str.substring(5));
}
}
Output
Substring = ForGeeks
Explanation:
- In the code, substring(5) is called on the StringBuilder object str, where index 5 corresponds to the character 'F'.
- All characters from index 5 up to the end of the sequence are extracted and returned as a new String, while the original StringBuilder remains unchanged.
Example 2. Extracting a Substring Using Start and End Index
class GFG{
public static void main(String[] args){
StringBuilder sb = new StringBuilder("GeeksForGeeks");
System.out.println(sb.substring(5, 8));
}
}
Output
For
Explanation:
- In the statement sb.substring(5, 8), index 5 is the starting position (inclusive), pointing to the character 'F'.
- Index 8 is the ending position (exclusive), so characters at indices 5, 6, and 7 are included in the result.
- The extracted substring "For" is returned as a new String, and the original StringBuilder sb remains unchanged.
Handling Invalid Index Values
Passing a negative index or an index greater than the length of the StringBuilder causes a StringIndexOutOfBoundsException at runtime.
class GFG{
public static void main(String[] args){
StringBuilder sb = new StringBuilder("JavaDeveloper");
try {
sb.substring(-3);
}
catch (Exception e) {
System.out.println(e);
}
}
}
Output
java.lang.StringIndexOutOfBoundsException: Range [-3, 13) out of bounds for length 13
Explanation: Negative start index is invalid. The method throws "StringIndexOutOfBoundsException" at runtime.