In Java (String immutability and concatenation), what is printed? String s = "ABC"; s.toLowerCase(); s += "def"; System.out.println(s);
-
AABC
-
Babc
-
CABCdef
-
DCompile Error
-
Eabcdef
Answer
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:
sis initially "ABC".s.toLowerCase()result is ignored.s += "def"concatenates and reassigns tos.
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:
s = "ABC" s.toLowerCase(); // no assignment → s still "ABC" s = s + "def" → "ABCdef" Print "ABCdef"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:
- "ABC" ignores the concatenation.
- "abc"/"abcdef" require assigning the lowercase result.
- Compile Error: code is valid.
Common Pitfalls: Expecting String methods to mutate the instance; they never do. Always store the returned value when transformation is desired.
Final Answer: ABCdef