Java String replace()
The replace() method in Java String is used to replace all occurrences of a specified character or substring with a new character or substring. It creates and returns a new string with the replacements, leaving the original string unchanged since strings in Java are immutable.Syntax:
Replacing a character
Replacing a substring
Replacing multiple occurrences
Difference between String replace() and replaceAll()
The main difference between String replace() and String replaceAll() lies in the way they handle replacements in a string:
String replace(char oldChar, char newChar) and String replace(CharSequence target, CharSequence replacement)
The replace() method replaces all occurrences of a specified character or substring with a new character or substring in the original string. It only considers exact matches for replacement, and both the oldChar or target and the newChar or replacement are treated as plain characters or character sequences, respectively.
The replacements are performed literally and don't use regular expressions.
String replaceAll(String regex, String replacement)
The replaceAll() method replaces all occurrences of a specified regular expression with the provided replacement string. Regular expressions allow for more advanced pattern matching and replacements in the string.
The regex parameter is a regular expression pattern to match, and the replacement parameter is the string that replaces the matched patterns. The replacements are performed based on the regular expression pattern matching.
In this example, the replace() and replaceAll() methods produce the same result because we are replacing exact occurrences of "A" with "X". However, if you were to use regular expressions, replaceAll() would offer more flexibility and power for pattern matching and replacements. For example, you could use "A\\s" in replaceAll() to replace "A" followed by a space with "X" and get different results.
It's important to note that the replace() method creates a new string with the replacements and does not modify the original string. If no occurrences of the target character or substring are found, the method returns the original string as it is.