Replace in Java: Replace Characters or Strings Easily

Updated on 29/08/20259,370 Views

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.

Java String replace(): What It Is and How It Works

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.

Common Exceptions While Using the replace() Method in Java

The replace() method has a specific feature where a null regular expression does not get accepted, this scenario is known as the NullPointerException.

Applications of the Java.String.replace() Operation

Java replace regex allows you to replace characters with a regular expression. The Java replace() method has several other functionalities, such as:

  • Assists in reading data from files with comma-separated values, where you can replace the delimiters with a space using this method to split the words.
  • Allows you to change and replace special characters for specific demands, like language and dialect. These replacements do not change the ulterior meaning of the word, it simply makes the string more understandable across the world.
  • Helps with handling URLs in Java, where you can encode the string to replace the desired characters.

replace() Method Syntax in Java

The replace() method in Java has two different overloads:

  1. replace(char oldChar, char newChar): This overload replaces all occurrences of the oldChar character with the newChar character in the string. The method returns a new string with the replacements.

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!".

  1. replace(CharSequence target, CharSequence replacement): This overload replaces all occurrences of the target sequence with the replacement sequence in the string. The target and replacement parameters can be either a String or a StringBuilder object. The method returns a new string with the replacements.

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!".

replace() Return Value

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.

How to Use replaceFirst() in Java Strings

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.

Examples of String replace() Method in Java

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:

Example 1: Replacing a single character

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().

Example 2: Replacing a substring

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().

Example 3: Replacing multiple characters

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().

Example 4: Replacing multiple characters using regex

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().

Understanding the replaceFirst() Method in Java

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.

Handling Exceptions with the replace() Method in Java

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);
    }
}

Conclusion

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. 

How Can upGrad Boost Your Java Skills?

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.

FAQs

1. How does the replace() method work in Java?

The replace() method in Java allows you to create a new string by replacing all occurrences of a specific character or substring. It does not modify the original string because Java strings are immutable. This method is commonly used in Java string manipulation, text formatting, and cleaning data for applications or user input handling. 

2. How to replace a character in a string in Java?

To replace a character in a string in Java, use string.replace('oldChar', 'newChar'). This returns a new string where every instance of the old character is replaced with the new one. Using this method ensures immutability while performing string replacement in Java applications, such as formatting text or processing user input.

3. How to replace multiple characters in a string in Java?

You can replace multiple characters in Java strings by chaining replace() calls or using replaceAll() with regular expressions. For example: string.replace("a","*").replace("e","#") or string.replaceAll("[aeiou]","*"). This is essential for advanced Java string manipulation, handling patterns, or cleaning multiple substrings efficiently. 

4. Can we change a string value in Java directly?

No, Java strings are immutable, so direct modification isn’t possible. Methods like replace() or replaceFirst() return a new string with replacements applied. This ensures safe and predictable string manipulation in Java, preventing accidental changes to original data while performing text processing or formatting tasks. 

5. What is the syntax of replace() in Java?

The syntax of replace() in Java includes: 

string.replace(char oldChar, char newChar) 

string.replace(CharSequence target, CharSequence replacement) 
Both return a new string after replacing characters or substrings. These are core methods for Java string manipulation, making it easier to perform safe and effective replacements without altering the original string. 

6. What does the replace() method return in Java?

The replace() method in Java returns a new string with the specified characters or substrings replaced. If the target is not found, it returns the original string. This makes it a reliable choice for Java string replacement tasks in applications like data formatting, text cleanup, and processing user input. 

7. What is the difference between replace() and replaceFirst() in Java?

replace() in Java replaces all occurrences of a character or substring, while replaceFirst() only replaces the first match. Both methods return new strings, making them safe for chaining. These methods are widely used in Java string manipulation for pattern-based replacements or selective updates. 

8. Can you replace characters in Java without using replace()?

Yes, characters can be replaced manually using loops, StringBuilder, or arrays. However, replace() and replaceFirst() are more efficient for Java string replacement, improving readability and minimizing errors when performing tasks like text formatting, data cleaning, or manipulating multiple substrings. 

9. What are some examples of using replace in Java?

Examples of Java string replacement include: 

"hello".replace('l','x') → "hexxo" 

"apple banana".replace("a","*") → "*pple b*n*n*" 
These illustrate how replace() in Java helps with string manipulation, text formatting, and cleaning data for real-world applications. 

10. Are there any exceptions with the replace() method in Java?

No, replace() in Java does not throw exceptions if the target character or substring isn’t found. It simply returns the original string, making it a safe and reliable method for Java string replacement and text processing tasks in both small and large-scale applications. 

11. How to replace a character in Java using object replacement?

For full substrings or CharSequence objects, replace() in Java can substitute matching sequences with another string object. Single characters cannot be replaced with objects. This technique is used in Java string manipulation for replacing words, phrases, or structured data like CSV fields safely.

12. How to replace spaces in a string in Java?

Use string.replace(" ", "_") or string.replaceAll("\\s", "_") to replace spaces in Java strings. This is useful for URL sanitization, formatting file names, or preparing strings for database and application input while maintaining immutability and safety in Java string manipulation. 

13. How to replace digits or numbers in a Java string?

You can replace digits in Java strings using replaceAll("\\d", "X"), which replaces all numbers with a placeholder. This is helpful for masking sensitive information, formatting numeric input, or cleaning text data while working with Java string manipulation safely. 

14. How to replace special characters in a Java string?

Special characters like !, @, or # can be replaced using replaceAll("[!@#]", "") in Java. This method is widely used for input validation, data sanitization, and cleaning strings before processing, ensuring safe and predictable string manipulation in Java applications. 

15. Can replace() handle null values in Java?

No, replace() in Java will throw a NullPointerException if the original string or target sequence is null. Always check for null before calling replace(). Proper handling ensures robust Java string manipulation without runtime errors in production applications. 

16. How to replace substrings using regex in Java?

Use string.replaceAll("regexPattern", "replacement") in Java to replace substrings matching a regex. This method is ideal for pattern-based text replacements, data validation, and cleaning strings in Java applications without modifying the original string.

17. How to replace only the last occurrence of a substring in Java?

Java does not have a built-in last occurrence replace method. Combine lastIndexOf() with substring() and replace() to update the final match. This approach is useful for tasks like editing the last entry in text files or structured data while maintaining immutable string safety.

18. Can replace() be chained in Java?

Yes, multiple replace() calls can be chained in Java for sequential replacements. For example: string.replace("a","*").replace("e","#"). Chaining improves efficiency and readability in Java string manipulation for replacing multiple characters or substrings in one operation. 

19. How to replace characters in a StringBuilder in Java?

StringBuilder allows mutable strings. Use sb.setCharAt(index, newChar) for in-place replacements without creating a new string. This is memory-efficient and faster than using replace() on immutable strings, ideal for repeated Java string manipulation in performance-critical applications. 

20. How to replace text in a file using Java strings?

To replace text in a file, read the content as a string, use replace() or replaceAll() to modify characters or substrings, then write it back. This method is commonly used for Java string replacement in file handling, log file updates, and automated text processing while preserving immutability. 

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Pavan Vadapalli

Author|900 articles published

Pavan Vadapalli is the Director of Engineering , bringing over 18 years of experience in software engineering, technology leadership, and startup innovation. Holding a B.Tech and an MBA from the India....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

text

Foreign Nationals

Disclaimer

  1. The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

  2. The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .