Java ProgramsStringsReplace Character in a String

Replace Character in a String in Java

beginner·  Strings  ·  String Manipulation

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.

Input
"banana", 'a' → 'o'
Output
bonono

Java Program

Java
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

bonono

Core Logic

Checking each character against the target, and appending either the replacement or the original, builds the result in one pass.

How It Works
  1. 1A for-each loop visits each character of the string in turn.
  2. 2if (c == target) checks whether the current character matches the one to be replaced.
  3. 3A match appends the replacement character instead; anything else appends the original character unchanged.
  4. 4The final StringBuilder holds the string with every target character swapped out.
For "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.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: Each character is visited once and appended to a result buffer that grows to match the input length.

Key Concepts

char comparisonStringBuilderfor-each loop

Approach 2: Using replace()

Java
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

bonono

Core Logic

In real code, there's no reason to loop manually — replace() already swaps every occurrence of a character in one call.

How It Works
  1. 1str.replace(target, replacement) takes the character to find and the character to substitute in its place.
  2. 2Internally, it performs the same kind of per-character comparison as the manual loop.
  3. 3No explicit loop or StringBuilder is 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.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

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

String.replace()

Approach 3: Java 8

Java
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

bonono

Core Logic

The same target-and-replace check can map a stream of character codes, then join the results back into a string.

How It Works
  1. 1str.chars() returns an IntStream of the string's character codes.
  2. 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. 3.map(String::valueOf) converts each resulting character into a one-character String.
  4. 4.collect(Collectors.joining()) concatenates them all back into a single result string.
Mapping "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.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: Each character is mapped once and Collectors.joining() rebuilds a result string holding all n characters.

Key Concepts

Streamchars()Collectors.joining()

Related Programs