The replace Method: Replacing Characters
What you'll learn: How to use replace(char oldChar, char newChar) to swap every occurrence of one character with another throughout a string.
What It Does
The replace method scans through an entire string and substitutes every instance of a specified character with a different character. Since strings are immutable, this operation returns a new string with the replacements applied—the original string remains unchanged.
Think of it like a "find and replace all" feature in a text editor, but limited to single characters rather than words or phrases.
The Method Signature
String replace(char oldChar, char newChar)
- oldChar: the character you want to replace
- newChar: the character you want to substitute in
- Returns: a new string with all replacements made
How to Use It
String original = "Hello World";
String modified = original.replace('o', 'a');
System.out.println(modified); // "Hella Warld"
System.out.println(original); // "Hella World" — unchanged
String path = "C:\\Users\\John\\Documents";
String unixPath = path.replace('\\', '/');
System.out.println(unixPath); // "C:/Users/John/Documents"
String noSpaces = "Java Programming".replace(' ', '_');
System.out.println(noSpaces); // "Java_Programming"
Important Behaviors
- If
oldChardoesn't exist in the string, the method returns the original string (or an identical copy) - All occurrences are replaced—there's no "replace first" or "replace last" variant
- Case matters:
'A'and'a'are different characters
Key Takeaway: Use replace(char oldChar, char newChar) to create a new string where every instance of one character is substituted with another—perfect for simple transformations like normalizing paths or removing/replacing single characters throughout text.