java.lang.StringBuilder substring(int start) and substring(int start, int end)
Description
sb.substring(start, sb.length());
Notes:
- An StringIndexOutOfBoundsException will be thrown if start is less than zero, or greater than the length of this object.
- This method is specified by subSequence in interface CharSequence.
Method Syntax
1.
public String substring(int start)
2.
public String substring(int start, int end)
Method Argument
| Data Type | Parameter | Description |
|---|---|---|
| int | start | the start index, inclusive. |
| int | end | the end index, exclusive. |
Method Returns
The substring() method returns the new string.
Compatibility
Requires Java 1.5 and up
Java StringBuilder substring() Example
Below is a java code demonstrates the use of substring() method of StringBuilder class. The example presented might be simple however it shows the behavior of the substring() method.
package com.javatutorialhq.java.examples;
/*
* A java example source code to demonstrate
* the use of substring() method of StringBuilder class
*/
public class StringBuilderSubstringExample {
public static void main(String[] args) {
// initialize the StringBuilder object
StringBuilder sb = new StringBuilder("test string abcd1234");
System.out.println("Contents of buffer:" + sb);
/*
* get the substring from this StringBuilder
* starting from
* index 2 to index 10
*/
int start = 2;
int end = 10;
String str = sb.substring(start, end);
System.out.println("Results:" + str);
}
}
The java example source code above, demonstrates the use of substring() method of StringBuilder class. Initially the code assigns a string “test string abcd1234” as initial contents of the StringBuilder. Then we use the subsequence to get a part of the sequence based from index 2 until the end index 10.
