For working professionals
For fresh graduates
More
Talk to our experts. We are available 7 days a week, 10 AM to 7 PM
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
Recommended Programs
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
How do you replace one or multiple characters in a Java string while keeping the original string unchanged?
In Java, strings are immutable, meaning their values cannot be modified once created. To handle string modifications safely, Java provides built-in methods like replace() and replaceFirst(). These methods allow you to generate a new string with the specified replacements applied. If you’re performing data cleaning, text formatting, or general string manipulation, knowing how to effectively replace in Java is essential for writing clean, bug-free code.
In this tutorial, we’ll explore the replace() method in Java, its syntax, return value, how it differs from replaceFirst(), and techniques for replacing single or multiple characters safely.
Want to master Java string manipulation and build cleaner, bug-free code? Explore upGrad’s Software Engineering Courses and learn Java hands-on with projects, mentorship, and job-ready skills.
This tutorial focuses on the Java string.replace() method, where a new one can replace every occurrence of the old character. This method returns a string to replace each old character with a new char or CharSequence.
Eager to expand your C programming skills and advance your career in high-demand tech domains? upGrad offers expertly designed programs to help you gain the advanced knowledge and practical skills that leading companies seek.
Since the launch of JDK 1.5, a new operation has been introduced in Java that allows you to replace an entire sequence of char values.
The replace() method has a specific feature where a null regular expression does not get accepted, this scenario is known as the NullPointerException.
Java replace regex allows you to replace characters with a regular expression. The Java replace() method has several other functionalities, such as:
The replace() method in Java has two different overloads:
Example Syntax:
String originalString = "Hello!";
String replacedString = originalString.replace('o', 'e');
System.out.println(replacedString); // Output: Helle!
In this example, the replace('o', 'e') call replaces all occurrences of the character 'o' with the character 'e' in the original string "Hello!", resulting in the replaced string "Helle!".
Example Syntax:
String originalString = "Hello!";
String replacedString = originalString.replace("Hello", "Hi");
System.out.println(replacedString); // Output: Hi!
In this example, the replace("Hello", "Hi") call replaces all occurrences of the substring "Hello" with the substring "Hi" in the original string "Hello!", resulting in the replaced string "Hi!".
The return value of the replace() method is a new string object that represents the original string with the modifications or replacements made. It does not modify the original string itself because strings in Java are immutable. Instead, the replace() method creates and returns a new string that reflects the modifications.
public class upGrad {
public static void main(String[] args) {
String originalString = "upGras";
String replacedString = originalString.replace('s', 'd');
System.out.println(originalString); // Output: upGras
System.out.println(replacedString); // Output: upGrad
}
}
In this example, the replace() method is called on the originalString object. The return value of the method is assigned to the replacedString variable. Notice that the originalString remains unchanged, while the replacedString contains the modified string with the replacements applied.
It's important to store and use the return value of the replace() method if you want to work with the modified string.
Similar to the Java.String.replace() method, this technique replaces the first substring of the string that has a match between the provided regular expression and the given replacement value.
Identical to the Java.String.replace() operation, this method also returns a resulting string.
public class upGrad {
public static void main(String[] args) {
// Example 1: Replacing a single character
String originalString1 = "upGrad";
String replacedString1 = originalString1.replace('u', 'U');
System.out.println("Example 1:");
System.out.println("Original string: " + originalString1);
System.out.println("Replaced string: " + replacedString1);
System.out.println();
// Example 2: Replacing a substring
String originalString2 = "upGrad";
String replacedString2 = originalString2.replace("Grad", "Skills");
System.out.println("Example 2:");
System.out.println("Original string: " + originalString2);
System.out.println("Replaced string: " + replacedString2);
System.out.println();
// Example 3: Replacing multiple characters
String originalString3 = "upGrad";
String replacedString3 = originalString3.replace("u", "U").replace("p", "P");
System.out.println("Example 3:");
System.out.println("Original string: " + originalString3);
System.out.println("Replaced string: " + replacedString3);
System.out.println();
// Example 4: Replacing multiple characters using regex
String originalString4 = "upGrad";
String replacedString4 = originalString4.replaceAll("[aeiou]", "*");
System.out.println("Example 4:");
System.out.println("Original string: " + originalString4);
System.out.println("Replaced string: " + replacedString4);
}
}
Output:
The above program demonstrates various examples of using Java's replace() method to replace characters or substrings within a string. Let's go through each example in detail:
In this example, the original string upGrad is assigned to the originalString1 variable. The replace() method is then used to replace the character 'u' with 'U', resulting in the modified string UpGrad. The original and replaced strings are printed using System.out.println().
In this example, the original string upGrad is assigned to the originalString2 variable. The replace() method is used to replace the substring "Grad" with "Skills", resulting in the modified string upSkills. Like the previous example, original and replaced strings are printed using System.out.println().
In this example, the original string upGrad is assigned to the originalString3 variable. Chaining multiple replace() methods is applied to replace the characters 'u' and 'p' with their uppercase counterparts, resulting in the modified string UpGrad. The original and replaced strings are then printed using System.out.println().
In this example, the original string upGrad is assigned to the originalString4 variable. The replaceAll() method is used with a regular expression [aeiou] to match and replace all vowels with an asterisk (*), resulting in the modified string *pGr*d. Finally, the original and replaced strings are printed using System.out.println().
public class upGrad {
public static void main(String[] args) {
// Replacing the first occurrence of a substring
String originalString5 = "upGrad";
String replacedString5 = originalString5.replaceFirst("a", "A");
System.out.println("replaceFirst Example:");
System.out.println("Original string: " + originalString5);
System.out.println("Replaced string: " + replacedString5);
}
}
This program begins by defining a class named upGrad. Inside the main method, a string variable originalString5 is declared and assigned the value "upGrad". This variable represents the original string on which the replacement operation will be performed.
The replaceFirst() method is then used on originalString5 to replace the first occurrence of the substring "a" with the character "A". The resulting replaced string is stored in the variable replacedString5.
Finally, to display the output, the program uses System.out.println() to print the heading "replaceFirst Example:". It then prints the original and replaced strings by concatenating them with appropriate messages.
The replace() method in Java does not throw any exceptions on its own. It is a safe operation that performs string replacement without raising any exceptions. Therefore, we do not need to handle specific exceptions using the replace() method.
However, it is important to note that the replace() method creates a new string with the replaced characters and returns it. The original string remains unchanged. So if we wish to store the result of the replace() operation, we must assign it to a variable or use it in some way.
Here is an example:
In the above example, the replace() method is used to replace the substring "World" with "upGrad". The original string remains unchanged, and the replaced string is stored in the replacedString variable.
Code:
public class upGrad {
public static void main(String[] args) {
String originalString = "Hello, World!";
String replacedString = originalString.replace("World", "upGrad");
System.out.println("Original string: " + originalString);
System.out.println("Replaced string: " + replacedString);
}
}
In conclusion, the replace in Java methods, replace(), replaceAll(), and replaceFirst(), provide efficient ways to modify strings without altering the original, thanks to Java’s immutable string design.
These methods offer flexibility for string manipulation in data cleaning, formatting, and application development. By understanding their syntax, return values, and differences, you can write cleaner, more reliable code.
upGrad offers industry-focused Java programs combining theory with hands-on coding and real-world projects. Expert mentorship ensures you gain practical skills and become job-ready for high-demand software development roles.
You can also access personalized career guidance or visit your nearest upGrad center for immersive learning. This approach equips you with both in-depth Java knowledge and practical experience, preparing you for a successful, future-ready tech career.
The replace() method in Java returns a new string by replacing all occurrences of a specified character or sequence with another. It does not modify the original string, as Java strings are immutable. The replace() method in Java returns a new string by replacing all occurrences of a specified character or sequence with another. It does not modify the original string, as Java strings are immutable.
To replace a character in a string in Java, use string.replace('oldChar', 'newChar'). It returns a new string where every instance of the old character is replaced with the new one. To replace a character in a string in Java, use string.replace('oldChar', 'newChar') . It returns a new string where every instance of the old character is replaced with the new one.
To replace multiple characters in a string in Java, chain multiple replace() calls or use regular expressions with replaceAll() if you're targeting patterns or groups of characters. To replace multiple characters in a string in Java, chain multiple replace() calls or use regular expressions with replaceAll() if you're targeting patterns or groups of characters.
No, Java strings are immutable, so you cannot change the original value. Instead, any method like replace() returns a new modified string, leaving the original unchanged. No, Java strings are immutable, so you cannot change the original value. Instead, any method like replace() returns a new modified string, leaving the original unchanged.
The syntax of the replace method in Java is: string.replace(char oldChar, char newChar) or string.replace(char oldChar, char newChar) or string.replace(CharSequence target, CharSequence replacement). string.replace(CharSequence target, CharSequence replacement) . It returns a new string with the specified replacement applied.
The replace() method returns a new string with characters or substrings replaced as specified. It does not throw an exception if the match isn't found—it simply returns the original string unchanged.
replace() replaces all occurrences, while replaceFirst() replaces only the first matching substring. Both return new strings, making them safe for chaining or complex manipulations. replace() replaces all occurrences, while replaceFirst() replaces only the first matching substring. Both return new strings, making them safe for chaining or complex manipulations.
Yes, you can use loops or StringBuilder to manually replace characters in Java. However, using replace() or replaceFirst() is more efficient and readable for most string replacement tasks.
An example: "hello".replace('l', 'x') returns "hexxo". Or, "apple banana".replace("a", "*") replaces all 'a' characters. These examples show how replace in Java is used in real applications. "apple banana".replace("a", "*") replaces all 'a' characters . These examples show how replace in Java is used in real applications.
No, the replace() method does not throw an exception even if the target character or string is not found. It simply returns the original string if there’s nothing to replace.
You can’t directly use object replacement for single characters, but for full substrings or sequences (as CharSequence), you can use replace() to substitute matching parts of the string with the desired object’s string value.
-9cd0a42cab014b9e8d6d4c4ba3f27ab1.webp&w=3840&q=75)
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
FREE COURSES
Start Learning For Free

Author|907 articles published