Introduction

Replacing characters in strings is a fundamental operation for text processing, data cleaning, and string manipulation. Java provides several methods for this task, each suited for different scenarios.


Method 1: replace() for Character Replacement

The simplest approach for exact character replacement.

 
public class ReplaceCharacter {

    public static void main(String[] args) {

        String original = "Hello World";

        // Replace a single character
        String result = original.replace('o', '0');
        System.out.println(result);

        // Replace a string
        String result2 = original.replace("World", "Java");
        System.out.println(result2);

        // Replace all occurrences
        String text = "aaa";
        String replaced = text.replace('a', 'b');
        System.out.println(replaced);
    }
}
 

Output

 
Hell0 W0rld
Hello Java
bbb
 

Key Features

  • Replaces all occurrences of the specified character or string.
  • Supports both char and String arguments.
  • Performs case-sensitive replacement.
  • Returns a new String object because strings are immutable.

Method 2: replaceAll() for Regex Patterns

Use replaceAll() when you need pattern matching with regular expressions.

Advertisement
 
public class ReplaceWithRegex {

    public static void main(String[] args) {

        String text = "Hello123World456";

        // Remove all digits
        String noDigits = text.replaceAll("\\d", "");
        System.out.println(noDigits);

        // Remove all vowels
        String cleaned = text.replaceAll("[aeiou]", "");
        System.out.println(cleaned);
    }
}
 

Output

 
HelloWorld
Hll123Wrld456
 

Key Features

  • Supports regular expressions.
  • Replaces every match in the string.
  • Useful for advanced text processing.
  • Slower than replace() because of regex processing.

Method 3: replaceFirst() for First Occurrence

Replace only the first occurrence of a matching pattern.

 
public class ReplaceFirst {

    public static void main(String[] args) {

        String text = "banana";

        // Replace first occurrence
        String result = text.replaceFirst("a", "x");
        System.out.println(result);

        // Using regex
        String text2 = "Hello123World456";
        String result2 = text2.replaceFirst("\\d+", "XXX");
        System.out.println(result2);
    }
}
 

Output

 
bxnana
HelloXXXWorld456
 

Key Features

  • Replaces only the first matching occurrence.
  • Supports regular expressions.
  • Useful when only the initial match should change.

Method 4: Using StringBuilder for Complex Replacements

When replacing characters at specific positions, converting the string to a character array provides complete control.

 
public class ReplaceWithStringBuilder {

    public static String replaceAtIndex(String text,
                                        int index,
                                        char replacement) {

        char[] chars = text.toCharArray();
        chars[index] = replacement;

        return new String(chars);
    }

    public static void main(String[] args) {

        String text = "Hello";

        String result = replaceAtIndex(text, 1, 'a');

        System.out.println(result);
    }
}
 

Output

 
Hallo
 

How It Works

  1. Convert the string to a character array.
  2. Replace the character at the required index.
  3. Create a new String from the updated array.

Advantages

  • Complete control over individual characters.
  • Ideal for position-based replacement.
  • Easy to customize.

Disadvantages

  • Requires manual index validation.
  • More code than replace().

Practical Examples

Example 1: Phone Number Formatting

 
String phone = "1234567890";

// Direct replacement
String formatted =
        phone.replace(
                "1234567890",
                "(123) 456-7890");

// Using regex
String formatted2 =
        phone.replaceAll(
                "(\\d{3})(\\d{3})(\\d{4})",
                "($1) $2-$3");
 

Example 2: HTML Entity Replacement

 
String html = "<div>Hello & goodbye</div>";

String escaped = html.replace("&", "&amp;")
                     .replace("<", "&lt;")
                     .replace(">", "&gt;");

System.out.println(escaped);
 

Output

 
&lt;div&gt;Hello &amp; goodbye&lt;/div&gt;
 

Example 3: Path Separator Conversion

 
String windowsPath = "C:\\Users\\Name\\Documents";

String unixPath = windowsPath.replace("\\", "/");

System.out.println(unixPath);
 

Output

 
C:/Users/Name/Documents
 

Performance Comparison

Method Supports Regex Replaces All Performance Best Use Case
replace() No Yes Fastest Simple character or string replacement
replaceAll() Yes Yes Slower Pattern-based replacement
replaceFirst() Yes First only Moderate Replace only the first match
Character Array No Manual Fast Position-based replacement

Best Practices

Use replace() for Simple Replacements

 
String result = text.replace('a', 'b');
 

Use replaceAll() Only When Regex Is Required

 
String result = text.replaceAll("\\d", "");
 

Avoid using regex when a simple replacement is sufficient.


Validate Index Before Manual Replacement

 
if (index >= 0 && index < text.length()) {
    // Safe replacement
}
 

Handle Null Values

 
public static String safeReplace(String text,
                                 String target,
                                 String replacement) {

    if (text == null) {
        return "";
    }

    return text.replace(target, replacement);
}
 

Frequently Asked Questions

Q1: What's the difference between replace() and replaceAll()?

Answer: replace() performs literal replacement, while replaceAll() treats the first argument as a regular expression.


Q2: Are there performance differences?

Answer: Yes. replace() is generally faster because it doesn't perform regex parsing.


Q3: Can I use regex with replace()?

Answer: No. Regular expressions are supported only by replaceAll() and replaceFirst().


Q4: How do I replace multiple different characters?

Answer: You can chain multiple replace() calls or use a character class with replaceAll().

Example:

 
String result = text.replaceAll("[abc]", "x");
 

Q5: Is the original string modified?

Answer: No. Strings in Java are immutable. Every replacement operation returns a new String.


Q6: How do I perform case-insensitive replacement?

Answer: Use the (?i) regex flag.

 
String result =
        text.replaceAll("(?i)java", "Python");
 

Q7: Can I use special characters in the replacement string?

Answer: Yes. When using replaceAll(), characters such as $ should be escaped or handled using Matcher.quoteReplacement().


Q8: How do I handle null values?

Answer: Check for null before calling the replacement method.

 
if (text != null) {
    text = text.replace("old", "new");
}
 

Q9: What happens if the character doesn't exist?

Answer: The original string is returned unchanged.


Q10: How do I replace a character at a specific position?

Answer: Convert the string into a character array, update the required index, and create a new String.

 
char[] chars = text.toCharArray();
chars[index] = replacement;

String result = new String(chars);