Introduction
The replace method in java is used to replace all the occurrences of a char with the given character. It first searches the String for a specified character and then returns a new string where the specified character(s) are replaced with the given one.

Syntax
public String replace(char oldChar, char newChar)
Parameters of the method
- Old Character
- New Character
- Target String
Return Value
New String (Replaced)
Implementation
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = value.length;
int i = -1;
char[] val = value;
while (++i < len) {
if (val[i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0; j < i; j++) {
buf[j] = val[j];
}
while (i < len) {
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(buf, true);
}
}
return this;
}
public String replace(CharSequence target, CharSequence replacement)
{
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
Example-1
public class Example1 {
public static void main(String[] args) {
String str = "IloveCodingNinjas";
String res = str.replace("i","e"); // Replace 'i' with 'e'
System.out.println(res);
res = rs.replace("e","i"); // Replace 'e' with 'i'
System.out.println(res);
}
}
Output
IloveCodengNenjas
IloveCodingNinjas
Explanation: Since we are calling the replace method on string str with oldChar = ‘i’ and newChar = ‘e’, therefore we got the first output .In the second call, we again called replace but this time with reversed parameters, therefore we got our original string.
Example-2
public class Example2{
public static void main(String args[]){
String s1="I Love Coding Ninjas I love Coding Ninjas";
String modifiedString=s1.replace("I","U");//replaces all occurrences of "I" to "U"
System.out.println(modifiedString);
}
}
Output
U Love Coding Ninjas U Love Coding Ninjas
Explanation: In the example above, replace method is called for string s1 with oldChar = ‘I’ and newChar = ‘U’, therefore we got our output with all the oldChar replaced with newChar ‘U’.
Frequently Asked Questions
What are methods in java?
Methods are the block of code that runs when they are called. In order to invoke a method, one needs to pass the parameter into it. They are called to perform specific tasks.
What are parameters in the method?
Parameters can be defined as the information that can be passed to the method. When passed, they act as variables inside the method.
What is the time-complexity of the operation of the replace method?
The time-complexity of the operation of the replace method would be of order O(n). Since searching can cost a linear time thus leads to O(n) complexity.