java.lang.StringBuilder substring(int start) and substring(int start, int end)

Description

On this document we will be showing a java example on how to use the substring() method of StringBuilder Class. This method is overloaded. One of the overloaded method is substring(int start) which takes the character sequences starting at the specified start index and will end at the last character. Meanwhile the second overloaded method is in the form substring(int start, int end) which takes the character sequence starting at the start index and will end at the end index. This two method is very similar and at some point will generate the same result if the end index specified is equal to the result of sb.length. For example: 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.

Sample Output

Below is the sample output when you run the above example.

StringBuilder substring() example output