Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
Strings in Java are objects backed internally by a char array. They are immutable, just like arrays; their values cannot be changed once initialized. This immutability makes them a fundamental data structure in Java, particularly for storing and manipulating text-based information.
The String class in Java contains several useful methods for manipulating strings. One such method is the replace() method, which can be used to replace characters or substrings in a string with new characters or substrings. This makes it an indispensable tool for text processing and manipulation in Java.
In this article, we’ll explore the intricacies of the Java String replace() method and how it can be leveraged to streamline string manipulation tasks.
Java String replace() Method
The replace() method in the Java String class replaces every occurrence of a character/substring with a new character/substring and returns the resulting string.
Syntax
The syntaxes for the two variants of replace() method are:
public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement)
Parameters
The parameters for replace() method are:
- oldChar – The old char to be replaced
- newChar – The new char to replace oldChar
- target – The target substring to be replaced
- replacement – The replacement substring
Return Value
The replace() method returns a string resulting from replacing all occurrences of oldChar/target with newChar/replacement, respectively.
Examples of Java String replace()
Let’s look at some examples to understand the usage of replace() method.
Example 1: Using replace(char old, char new)
public class StringReplaceExample {
public static void main(String[] args) {
String str = "Hello World";
String newStr = str.replace('l', 'w');
System.out.println(newStr);
}
}
Output:
Hewwo Word
Example 2: Using replace(String target, String replacement)
public class StringReplaceExample {
public static void main(String[] args) {
String str = "Hello World";
String newStr = str.replace("World", "Universe");
System.out.println(newStr);
}
}
Output:
Hello Universe
Exceptions with replace() Method
If we pass a null regular expression to replace(), it results in NullPointerException.
For example:
public class StringReplaceExample {
public static void main(String[] args) {
String str = "Hello";
String regex = null;
try {
str = str.replace(regex, "Hi");
System.out.println(str);
} catch (NullPointerException e) {
System.out.println("NullPointerException occurred: " + e.getMessage());
}
}
}
Output:
NullPointerException occurred: replace(CharSequence target, CharSequence replacement)
This is because replace() expects a valid regular expression and cannot work with a null value.
Java String replaceFirst()
Along with replace(), String class also provides replaceFirst() method which replaces only the first occurrence of a substring.
Syntax
public String replaceFirst(String regex, String replacement)
Parameters
regex – The regular expression to match
replacement – The string to replace the regex
Return Value
It returns a string with the first matching regex replaced.
Example of Java String replaceFirst()
public class StringReplaceExample {
public static void main(String[] args) {
String str = "Hello World";
String result = str.replaceFirst("l", "w");
System.out.println(result);
}
}
Output:
Hewlo World
Conclusion
In conclusion, the Java String replace() method is valuable for manipulating strings. It allows you to replace all occurrences of a character or substring with a new character or substring in a string. There are two variants of the method, one for replacing characters and another for replacing substrings. It returns a new string with the replacements, leaving the original string unchanged. However, it’s important to note that passing a null regular expression to replace() will result in a NullPointerException.
Additionally, Java offers a replaceFirst() method to replace only the first occurrence of a substring in a string, providing flexibility in string manipulation.
