The replace() method in Java is used to replace characters or substrings within a string. It is a method of the String class and allows you to replace one or more occurrences of a specified character or substring with another character or substring.
Syntax 1:
replace(char oldChar, char newChar)
Note: Replaces all occurrences of the specified oldChar with the newChar in the string.
Syntax 2:
replace(CharSequence oldSubstring, CharSequence newSubstring)
Note: Replaces all occurrences of the specified oldSubstring with the newSubstring in the string.
Return Value: The method returns a new String with the specified replacements made. The original string is not modified, as strings in Java are immutable.
Example:
public class ReplaceExample {
public static void main(String[] args) {
String str = "Hello World";
// Replace 'l' with '1'
String result = str.replace('l', '1');
// Print the resulting string
System.out.println(result);
}
}
Output:
In this example, every occurrence of the character ‘l’ is replaced with ‘1’.
Replacing a substring with another substring
public class ReplaceExample {
public static void main(String[] args) {
String str = "Hello World";
// Replace "World" with "Friends"
String result = str.replace("World", "Friends");
// Print the resulting string
System.out.println(result);
}
}
Output:
Replace Multiple Occurrences of a Substring
You can replace all occurrences of a substring with another substring.
public class ReplaceExample {
public static void main(String[] args) {
String str = "Potato, Tomato, Cauliflower, Cabbage, Potato";
// Replace all occurrences of "Potato" with "Onion"
String result = str.replace("Potato", "Onion");
// Print the resulting string
System.out.println(result);
}
}
Output:
Replace String with No Matches
If the character or substring to be replaced is not found in the string, the original string is returned unchanged.
public class ReplaceExample {
public static void main(String[] args) {
String str = "Hello World";
// Try to replace "abc" with "def", which does not exist in the string
String result = str.replace("abc", "def");
// Print the resulting string (unchanged)
System.out.println(result);
}
}
Output: