Difficulty: Easy
Correct Answer: ABCdef
Explanation:
Introduction / Context:
Here we check whether calling toLowerCase()
without assignment changes a String and how concatenation with +=
works for immutable Strings in Java. The operation order determines the final printed value.
Given Data / Assumptions:
s
is initially "ABC".s.toLowerCase()
result is ignored.s += "def"
concatenates and reassigns to s
.
Concept / Approach:
Strings are immutable; methods return new objects rather than mutating the original. If you do not store the returned String from toLowerCase()
, s
remains unchanged ("ABC"). The +=
operation creates a new String "ABCdef" and assigns it to s
.
Step-by-Step Solution:
Verification / Alternative check:
If you wanted "abcdef", you would need s = s.toLowerCase();
before concatenation or write ("ABC".toLowerCase() + "def")
.
Why Other Options Are Wrong:
Common Pitfalls:
Expecting String methods to mutate the instance; they never do. Always store the returned value when transformation is desired.
Final Answer:
ABCdef
Discussion & Comments