java.lang.StringBuffer replace(int start,int end,String str)

Description :

This java tutorial shows how to use the replace(int start,int end,String str) method of StringBuffer class under java.lang package.

This method replaces the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end – 1 or to the end of the sequence if no such character exists. First the characters in the substring are removed and then the specified String is inserted at start. Make a note that this sequence will be lengthened to accommodate the specified String if necessary.

Method Syntax :

public StringBuffer replace(int start,int end,String str)

Parameter Input :

DataType Parameter Description
int start the beginning index
int end the ending index
String str the String that will be replaced on the stringbuffer contents.

Method Returns :

The replace() method of String class returns this StringBuffer object with its characters replaced by the str method argument.

Compatibility Version :

Requires Java 1.2 and up

Java Code Example :

This java example source code demonstrates the use of replace(int start,int end,String str) method of StringBuffer class. Initially the code assigns a string “javatutorialhq.com” as initial contents of the string buffer. Then we use replace method to replace the characters from index 2 to index 5 with string “VATUTO”. As you would have noticed the number of characters is greater that the number than the length of index 2 to 5. Remember the rule that this sequence will be lengthened to accommodate the specified String if necessary.

package com.javatutorialhq.java.examples;

/*
 * This example source code demonstrates the use of 
 * replace(int start,int end,String str) method of StringBuffer class
 */

public class StringBufferReplace {

	public static void main(String[] args) {

		// initialize the StringBuffer object
		StringBuffer sb = new StringBuffer("javatutorialhq.com");
		System.out.println("Contents of buffer:" + sb);

		int start = 2;
		int end = 5;
		String str = "VATUTO";
		
		
		// Replace the characters from index 2 to index 5
		sb.replace(start, end, str);
		System.out.println("New Contents of Buffer:"+sb);
		
		


	}
}

Sample Output :

Running the above example source code will give the following output

replace(int start,int end,String str) method example

replace(int start,int end,String str) method example

Exception Scenario :

StringIndexOutOfBoundsException

The above exception will be if the following condition has been met:

  • if start is negative
  • start is greater than the StringBuffer length
  • start is greater than the end index

Suggested Reading List :

References :