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.
The replace( ) method has two forms. The first replaces all occurrences of one character in the invoking string with another character.
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:
Java String replace() Method – Interview Questions
Q 1: What is replace() method used for?
Q 2: Does replace() modify original string?
Q 3: Is replace() case-sensitive?
Q 4: What are common replace() variations?
Q 5: Can replace() work with characters?
Java String replace() Method – Objective Questions (MCQs)
Q1. What does the replace() method do?
Q2. What will "Java".replace("a", "o") return?
Q3. What is the return type of split() method?
Q4. Does the replace() method modify the original string?
Q5. What will "Techfliez".replace("fliez", "World") return?