In Java, the replace() method is used to replace characters or character sequences within a string.
You can use it to substitute a specific character or substring with another.
For pattern-based replacements using regular expressions, Java provides the replaceAll() method, which replaces all occurrences that match the given regex pattern.
Below, I’ve shared several examples demonstrating how to replace parts of a string using both replace() and replaceAll().
1. The replace(char oldChar, char newChar) method in Java is used to replace all occurrences of a specific character (oldChar) with another character (newChar) in a string.
✅ Syntax:
public String replace(char oldChar, char newChar)
✅ Example:
String str = “banana”;
String result = str.replace(‘n’, ‘c’);
System.out.println(result); // Output: bacaca
2.The replace(CharSequence target, CharSequence replacement) method is used to replace all occurrences of a target substring with a replacement substring.
✅ Syntax:
public String replace(CharSequence target, CharSequence replacement)
✅ Example:
String str = “I love learning Java”;
🔹 replaceAll() – Replace Using Regular Expressions
🔹The replaceAll() method is used to replace all occurrences of substrings that match a specified regular expression with a given replacement string.
✅ Syntax:
public String replaceAll(String regex, String replacement)
regex: The regular expression to match substrings.
replacement: The string to replace the matched parts.
✅ Example: Replace all digits with *
public class ReplaceAllExample {
public static void main(String[] args) {
String str = "User123Data456";
String result = str.replaceAll("\\d", "*");
System.out.println(result); // Output: User***Data***
}
}