Difficulty: Easy
Correct Answer: AAACCC
Explanation:
Introduction / Context:
This question examines the equals contract and polymorphism. Both variables refer to the same String object; one is typed as String, the other as Object. Because String overrides equals to compare character sequences, symmetry should hold: a.equals(b) implies b.equals(a).
Given Data / Assumptions:
s
and o
refer to the same instance.
Concept / Approach:
The dynamic type of o
is String even though its static type is Object. Calling equals dispatches to String.equals in both checks: first directly on s; second via virtual dispatch on o (which is a String at runtime).
Step-by-Step Solution:
Evaluate s.equals(o): s is "foo"; o is the same "foo" instance ⇒ true ⇒ prints "AAA".Evaluate o.equals(s): o is a String at runtime; s is also String with equal content ⇒ true ⇒ prints "CCC".Concatenate outputs: "AAACCC".
Verification / Alternative check:
Replace o = new Object()
and note s.equals(o) becomes false while o.equals(s) is Object.equals (identity), also false.
Why Other Options Are Wrong:
Other options assume asymmetry or inequality, which violates String’s equals contract given same content and same instance.
Common Pitfalls:
Confusing static vs dynamic type in virtual method dispatch; assuming equals is reference-equality-only for String (it is content-based).
Final Answer:
AAACCC
Discussion & Comments