In this tutorial, we will discuss the Java StringBuilder substring() method with the help of examples.
The syntax of substring() method is:
sb.substring(4) //substring starting from index 4 till end sb.substring(2, 5) //substring from index 2 till index 5
Here, sb
is an object of StringBuilder
class.
substring() Description
There are two variations of substring() method in Java StringBuilder class.
public String substring(int startIndex): It returns a substring starting from the specified index startIndex
till the end of the given character sequence.
public String substring(int startIndex, int endIndex): It returns a substring starting from the specified index startIndex
till the specified index endIndex
.
substring() Parameters
It can take upto two parameters. The endIndex
parameter is optional.
- startIndex: Specifies the start position of the substring
- endIndex: Specifies the end of the substring
This method throws StringIndexOutOfBoundsException
, if any of the following condition occurs:
- If
startIndex
< 0 or >= length of the string represented by StringBuilder. - If
endIndex
< 0 or >= length of the string. - if
startIndex
>endIndex
.
substring() Return Value
Returns a substring based on the specified indexes.
Example 1: When only startIndex is specified
class JavaExample{ public static void main(String[] args) { StringBuilder sb = new StringBuilder("BeginnersBook"); //substring begins from index 9 String subStr = sb.substring(9); System.out.println("Substring from index 9: "+subStr); } }
Output:

Example 2: When both startIndex and endIndex are specified
class JavaExample{ public static void main(String[] args) { StringBuilder sb = new StringBuilder("BeginnersBook"); //substring from 0 till 5 String subStr = sb.substring(0, 5); System.out.println("Substring from index 0 to 5: "+subStr); } }
Output:

Example 3: When startIndex is greater than endIndex
class JavaExample{ public static void main(String[] args) { StringBuilder sb = new StringBuilder("BeginnersBook"); //when startIndex is greater than endIndex String subStr = sb.substring(5, 2); System.out.println("Substring: "+subStr); } }
Output:

Similarly, if any of the specified indexes are negative or >= to the string length then the method will throw this exception.