In this tutorial, we will discuss the Java StringBuffer 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 StringBuffer class.
substring() Description
There are two variations of substring() method in Java StringBuffer 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 StringBuffer. - If
endIndex< 0 or >= length of the string. - if
startIndex>endIndex.
substring() Return Value
Returns a substring based on the specified indexes.
Example 1: Only startIndex is given
class JavaExample{
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("BeginnersBook");
//substring begins from index 9
String subStr = sb.substring(9);
System.out.println("Substring from index 9: "+subStr);
}
}
Output:

Example 2: Substring using start and end indexes
class JavaExample{
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("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: If startIndex is greater than endIndex
class JavaExample{
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("BeginnersBook");
//when startIndex is greater than endIndex
String subStr = sb.substring(5, 2);
System.out.println("Substring: "+subStr);
}
}
Output:

Leave a Reply