java.lang.StringBuffer substring(int start,int end)

Java Code Example :

This java example source code demonstrates the use of substring(int start,int end)  method of StringBuffer class. Initially the code assigns a string “” as initial contents of the string buffer. Then we use the substring method with index 5 as starting point until index of 8 in getting the character sequences of the buffer. Calling this method returns a new sets of characters which comes from the stringbuffer object and chopped from the starting index until the end index both are specified as method argument.

Make a note that StringIndexOutOfBoundsException will be thrown if start or end are negative or greater than length(), or start is greater than end.

This method is overloaded with substring(start). This is similar however in this case we specified the end index as method argument not unlike the other one which implicitly have the end index as the stringbuffer length.


 * This example source code demonstrates the use of 
 * substring(int start,int end) method of StringBuffer class

public class StringBufferSubstringStartEnd {

	public static void main(String[] args) {

		// initialize the StringBuffer object
		StringBuffer sb = new StringBuffer("");
		System.out.println("Contents of buffer:" + sb);
		// get the string from buffer from index 5 to index 8
		int start = 5;
		int end = 8;
		String str = sb.substring(start,end);		


Sample Output :

Running the above example source code will give the following output

substring(int start,int end) method example

substring(int start,int end) method example

Suggested Reading List :

References :