Replace Character in a String in Java
Problem
Replacing a character means swapping every occurrence of one specific character in a string for a different one, leaving everything else untouched.
Given a string and two characters, replace every occurrence of the first character with the second.
Java Program
public class ReplaceCharacter {
public static void main(String[] args) {
String str = "banana";
char target = 'a';
char replacement = 'o';
StringBuilder result = new StringBuilder();
for (char c : str.toCharArray()) {
if (c == target) {
result.append(replacement); // swap the target character out
} else {
result.append(c); // pass everything else through unchanged
}
}
System.out.println(result.toString());
}
}Output
Core Logic
Checking each character against the target, and appending either the replacement or the original, builds the result in one pass.
- 1A for-each loop visits each character of the string in turn.
- 2
if (c == target)checks whether the current character matches the one to be replaced. - 3A match appends the
replacementcharacter instead; anything else appends the original character unchanged. - 4The final
StringBuilderholds the string with every target character swapped out.
"banana" with target 'a' and replacement 'o', every 'a' becomes 'o', producing "bonono".Key Point: Only exact matches to target are replaced — 'b' and 'n' pass straight through untouched, since they aren't the character being targeted.
Why: Each character is visited once and appended to a result buffer that grows to match the input length.
Key Concepts
Approach 2: Using replace()
public class ReplaceCharacterBuiltin {
public static void main(String[] args) {
String str = "banana";
// replace() swaps every occurrence of the target character in one call
System.out.println(str.replace('a', 'o'));
}
}
Output
Core Logic
In real code, there's no reason to loop manually — replace() already swaps every occurrence of a character in one call.
- 1
str.replace(target, replacement)takes the character to find and the character to substitute in its place. - 2Internally, it performs the same kind of per-character comparison as the manual loop.
- 3No explicit loop or
StringBuilderis needed in your own code.
"banana".replace('a', 'o') returns "bonono" in a single call.Key Point: This is the version to actually use — the manual loop exists only to show what replace() is conceptually doing under the hood.
Why: replace() still has to scan the whole string and build a new one with the substitutions made, but that work happens inside the JDK instead of your own loop.
Key Concepts
Approach 3: Java 8
import java.util.stream.Collectors;
public class ReplaceCharacterStream {
public static void main(String[] args) {
String str = "banana";
char target = 'a';
char replacement = 'o';
// Maps each character to the replacement if it matches, then joins them back into a String
String result = str.chars()
.mapToObj(c -> c == target ? replacement : (char) c)
.map(String::valueOf)
.collect(Collectors.joining());
System.out.println(result);
}
}
Output
Core Logic
The same target-and-replace check can map a stream of character codes, then join the results back into a string.
- 1
str.chars()returns anIntStreamof the string's character codes. - 2
.mapToObj(c -> c == target ? replacement : (char) c)maps each code to the replacement character if it matches the target, or leaves it unchanged otherwise. - 3
.map(String::valueOf)converts each resulting character into a one-characterString. - 4
.collect(Collectors.joining())concatenates them all back into a single result string.
"banana" character by character replaces each 'a' with 'o', and Collectors.joining() reassembles "bonono".Key Point: The ternary inside mapToObj() is the same target check the loop version uses in its if statement — streams just change how it's applied across the string.
Why: Each character is mapped once and Collectors.joining() rebuilds a result string holding all n characters.