Bird
0
0

You want to replace all occurrences of the letter 'a' with 'b' in a string input. Which code correctly does this considering string immutability?

hard📝 Application Q15 of 15
Java - Strings and String Handling
You want to replace all occurrences of the letter 'a' with 'b' in a string input. Which code correctly does this considering string immutability?
Ainput.replace('a', 'b'); System.out.println(input);
Binput.charAt(0) = 'b'; System.out.println(input);
Cinput.toCharArray()[0] = 'b'; System.out.println(input);
Dinput = input.replace('a', 'b'); System.out.println(input);
Step-by-Step Solution
Solution:
  1. Step 1: Understand replace() returns new string

    The replace() method returns a new string with replacements but does not change the original.
  2. Step 2: Assign the new string back to input

    To update input, assign the result of replace() back to it before printing.
  3. Final Answer:

    input = input.replace('a', 'b'); System.out.println(input); -> Option D
  4. Quick Check:

    Assign replace result to variable to update string [OK]
Quick Trick: Assign replace() result to variable to update string [OK]
Common Mistakes:
  • Calling replace() without assignment
  • Trying to assign to charAt() or array elements
  • Expecting original string to change automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes