0
0
JavaHow-ToBeginner · 3 min read

How to Replace Character in String in Java - Simple Guide

In Java, you can replace characters in a string using the replace(char oldChar, char newChar) method of the String class. This method returns a new string where all occurrences of oldChar are replaced with newChar.
📐

Syntax

The syntax to replace a character in a string is:

String newString = originalString.replace(oldChar, newChar);
  • originalString: The string you want to change.
  • oldChar: The character you want to replace.
  • newChar: The character you want to use instead.
  • newString: The new string with replacements.

Note that strings in Java are immutable, so replace() does not change the original string but returns a new one.

java
String newString = originalString.replace('a', 'b');
💻

Example

This example shows how to replace all occurrences of the character 'a' with 'o' in a string.

java
public class ReplaceCharExample {
    public static void main(String[] args) {
        String original = "java programming";
        String replaced = original.replace('a', 'o');
        System.out.println("Original: " + original);
        System.out.println("Replaced: " + replaced);
    }
}
Output
Original: java programming Replaced: jovo progromming
⚠️

Common Pitfalls

  • Trying to modify the original string directly will not work because strings are immutable in Java.
  • Using replace() with strings instead of characters requires different method overloads.
  • Confusing replace() with replaceAll(), which uses regular expressions.

Example of a common mistake and the correct way:

java
// Wrong: This does not change the original string
String text = "apple";
text.replace('a', 'b'); // result ignored
System.out.println(text); // prints "apple"

// Right: Assign the result to a new string or the same variable
text = text.replace('a', 'b');
System.out.println(text); // prints "bpple"
Output
apple bpple
📊

Quick Reference

MethodDescriptionExample
replace(char oldChar, char newChar)Replaces all occurrences of a character"hello".replace('l', 'p') → "heppo"
replace(CharSequence target, CharSequence replacement)Replaces all occurrences of a string"hello".replace("ll", "yy") → "heyyo"
replaceAll(String regex, String replacement)Replaces all substrings matching regex"hello123".replaceAll("\\d", "*") → "hello***"

Key Takeaways

Use String's replace(char oldChar, char newChar) to replace characters in Java strings.
Strings are immutable; always assign the result of replace() to a variable.
replace() replaces all occurrences of the old character, not just the first.
For replacing substrings or patterns, use replace(CharSequence, CharSequence) or replaceAll().
Remember that replaceAll() uses regular expressions, so be careful with special characters.