Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Java - Strings and String Handling
What will be the output of this code?
String s1 = "abc";
String s2 = s1.replace('a', 'z');
System.out.println(s1 + " " + s2);
Azbc abc
Babc zbc
Cabc abc
Dzbc zbc
Step-by-Step Solution
Solution:
  1. Step 1: Understand replace() method behavior

    The replace() method returns a new string with replacements; original string remains unchanged.
  2. Step 2: Check values of s1 and s2

    s1 is "abc"; s2 is "zbc" after replacing 'a' with 'z'.
  3. Final Answer:

    abc zbc -> Option B
  4. Quick Check:

    replace() returns new string; original unchanged [OK]
Quick Trick: replace() returns new string; original string stays same [OK]
Common Mistakes:
  • Assuming original string changes after replace()
  • Mixing order of printed strings
  • Expecting runtime error on replace()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes