Java equals symmetry between String and Object references to the same string: what prints? public class Test178 {\n public static void main(String[] args) {\n String s = "foo";\n Object o = (Object) s;\n if (s.equals(o)) { System.out.print("AAA"); } else { System.out.print("BBB"); }\n if (o.equals(s)) { System.out.print("CCC"); } else { System.out.print("DDD"); }\n }\n}

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.
  • String.equals tests content equality against any Object, returning true when the other is a String with equal contents.


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

More Questions from Java.lang Class

Discussion & Comments

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