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

Description

On this document we will be showing a java example on how to use the StringBuilder replace(int start, int end, String str) method of StringBuilder Class. Basically the replace() 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.)

Notes:

  • The replace() method throws StringIndexOutOfBoundsException if the start index supplied is negative, greater than the length(), or its greater than the end index supplied.

Method Syntax

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

Method Argument

Data Type Parameter Description
int start The beginning index, inclusive.
int end The ending index, exclusive
String str String that will replace previous contents.

Method Returns

The replace() method returns this StringBuilder object that is the result of replacing some of it’s characters as defined by the method arguments.

Compatibility

Requires Java 1.5 and up

Java StringBuilder replace() Example

Below is a java code demonstrates the use of replace() method of StringBuilder class. The example presented might be simple however it shows the behavior of the replace() method.

package com.javatutorialhq.java.examples;


/*
 * A java example source code to demonstrate
 * the use of replace() method of StringBuilder class
 */

public class StringBuilderReplaceExample {

	public static void main(String[] args) {

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

		int start = 2;
		int end = 5;
		String str = "TRATUTO";

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

	}
}

The above java example source code demonstrates the use of replace() method of StringBuilder class. Initially the code assigns a string “javatutorialhq.com” as initial contents of the StringBuilder. Then we use replace method to replace the characters from index 2 to index 5 with string “TRATUTO”. 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.

Sample Output

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

StringBuilder replace() example output