In Java Strings (immutability and case conversion), what is printed by the following code? String x = "xyz"; x.toUpperCase(); /* Line 2 */ String y = x.replace('Y', 'y'); y = y + "abc"; System.out.println(y);

Java Programming Java.lang Class Difficulty: Easy
Choose an option
  • A
    abcXyZ
  • B
    abcxyz
  • C
    xyzabc
  • D
    XyZabc
  • E
    XYZabc

Answer

Correct Answer: xyzabc

Explanation

Introduction / Context: This checks Java String immutability and the behavior of common methods like toUpperCase and replace. Because Strings are immutable, methods return new String instances rather than modifying the original object.

Given Data / Assumptions:

  • x is "xyz".
  • x.toUpperCase() result is ignored.
  • replace is called with \'Y\' which is not present in "xyz".
  • Finally, "abc" is concatenated to y.

Concept / Approach: Since the uppercase call is ignored, x remains "xyz". Calling x.replace(\'Y\', \'y\') returns the unchanged "xyz" because there is no uppercase Y to replace. Concatenation produces "xyzabc".

Step-by-Step Solution:

x = "xyz" x.toUpperCase(); // discarded → x still "xyz" y = x.replace(\'Y\', \'y\') → "xyz" y = y + "abc" → "xyzabc" Prints "xyzabc"

Verification / Alternative check: If we had written x = x.toUpperCase(), then x would become "XYZ", and replacing \'Y\' with \'y\' would yield "XyZ" and final "XyZabc". That is not what this code does.

Why Other Options Are Wrong:

  • "abcxyz" or "XyZabc": would require assigning the uppercase result back to x first.
  • "abcXyZ" or "XYZabc": also depend on the missed reassignment.

Common Pitfalls: Forgetting Strings are immutable and assuming methods mutate in place. Always capture the returned String if a change is desired.

Final Answer: xyzabc

Discussion & Comments
No comments yet. Be the first to comment!
Join Discussion