java.lang.StringBuilder replace(int start, int end, String str)
Description
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.