VOOZH about

URL: https://www.geeksforgeeks.org/java/stringbuilder-replace-in-java-with-examples/

⇱ StringBuilder replace() in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

StringBuilder replace() in Java with Examples

Last Updated : 24 Jan, 2026

The replace(int start, int end, String str) method of StringBuilder is used to replace a specified range of characters with a given string. It modifies the existing StringBuilder object directly, making it efficient for frequent updates to strings.


Output
Hello Java

Explanation:

  • A StringBuilder object is created with the initial value "Hello World".
  • The replace(6, 11, "Java") method replaces the characters from index 6 to 10 ("World") with "Java".
  • The modified StringBuilder is printed, showing the updated string "Hello Java".

Syntax

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

Parameters: This method accepts three parameters:

  • start - Starting index (inclusive)
  • end - Ending index (exclusive)
  • str - String to replace the specified range

Return Value: This method returns StringBuilder object after successful replacement of characters. 

Note:

  • The character at index start is included, while the character at index end is excluded.
  • If start == end, the string is inserted at that position.

Examples of StringBuilder replace() Method

Example 1: Basic Replacement


Output
Original: WelcomeGeeks
After: We are Geeks

Explanation: Characters from index 1 to 6 are replaced with "e are ".

Example 2: Replacing a Substring in the Middle


Output
I like Java

Explanation: The replace(7, 13, "Java") call replaces the substring "Python" with "Java" in the middle of the StringBuilder.

Example 3: Inserting Using replace()


Output
Java Programming

Explanation: When start and end are the same, the string is inserted at that position.

Example 4: Replacing Entire String


Output
New Value

Explanation: It replaces all characters from index 0 to the length of the StringBuilder, effectively replacing the entire string with "New Value".

Example 5: Invalid Index Handling

Output:

StringIndexOutOfBoundsException

Explanation: The end index exceeds the length of the StringBuilder.

Comment
Article Tags: