Difficulty: Easy
Correct Answer: Compilation fails.
Explanation:
Introduction / Context:
This snippet distinguishes between the APIs of immutable String
and mutable StringBuilder
/StringBuffer
. It also highlights that ignoring the return value of substring
does not change the original String, and that append
is not a member of String
at all.
Given Data / Assumptions:
d
is declared as String
.d.substring(1,7)
is called but its result is discarded.d = "w" + d;
creates a new String.d.append("woo")
is attempted on a String
.
Concept / Approach:
Only StringBuilder
and StringBuffer
provide append
. Invoking append
on a String
is a compile-time error: cannot find symbol: method append(java.lang.String). If a mutable sequence was intended, declare StringBuilder d = new StringBuilder("bookkeeper");
and then use d.append(...)
.
Step-by-Step Solution:
d.append("woo")
fails because String
has no such method. Therefore the program does not run; no runtime output is produced.
Verification / Alternative check:
If we replaced line 4 with d = d + "woo";
, output would be wbookkeeperwoo
. If we used StringBuilder
, we could build efficiently without intermediate strings.
Why Other Options Are Wrong:
append
exists on String
or that substring
mutated the original; neither is true.
Common Pitfalls:
Treating Strings as mutable, or assuming substring
changes the receiver. Always capture returned values from String operations.
Final Answer:
Compilation fails.
Discussion & Comments