Java String replace() Method
In Java, we can replace occurrences of a character or substring using the replace() method, which has two variations:
- replace(char oldChar, char newChar)
- replace(CharSequence oldString, CharSequence newString)
These methods return a new string with the replacements made. Note that the original string is not modified since strings in Java are immutable.
Syntax
The replace() method in Java has two syntaxes.
-
- Syntax for Replacing a Character:
-
- Syntax for Replacing a Substring:
Parameters Values
To replace all occurrences of a particular character with another character in Java, we use the first syntax of the replace() method in Java.
- oldChar - The character to be replaced in the string.
- newChar - The character to be used instead of oldChar in the string.
To replace all occurrences of a particular string or substring with another string or substring, we use the second syntax of the replace() method in Java.
- oldString - The string or substring to be replaced in the original string.
- newString - The string or substring to be used in place of the old string or substring in the original string.
Return Value
The replace() method in Java returns a new string where each occurrence of a character/word/sentence has been replaced with a new character/word/sentence.
If there is no match for the new character/word/sentence, the replace() in Java method returns the original string.
Exception
We cannot use null as an argument in the replace() method. If we use null as an argument, the system will throw a NullPointerException.
Internal Implementation
Here is the internal implementation of the replace method in Java:
Java String replace() Method Examples
Example 1: Java String replace(char old, char new) Method
Replacing One Character with Another in Java Using replace() in java.
Output:
In the above code, we display the string object "G00d M0rning" and then call the replace() method on this object. We replace '0' with 'o' and then print the modified string on the screen.
Example 2: Java String replace(CharSequence target, CharSequence replacement) Method
Example of the replace(CharSequence oldString, CharSequence newString) method in Java:
Output:
Exception 3: Exception in Java replace() method
Output
Conclusion
- The replace() in Java is a built-in method of the Java String class.
- It is utilized to replace characters or substrings within a string.
- If the replacement does not find a match, the original string remains unchanged and is returned as the result.
FAQs
Q. What implementations are available for the replace() in Java String class?
A. There are various other built-in method implementations, such as:
- replaceFirst()
- replaceAll()
Q. Do replaceAll() and replace() work the same?
A. replaceAll() is an advanced implementation of replace() where regular expressions can be used to replace in Java all occurrences of characters in a string.