Java Object vs String equality symmetry: given the outputs A/B/C/D, which two are printed? String s = 'hello'; Object o = s; if (o.equals(s)) { System.out.println("A"); } else { System.out.println("B"); } if (s.equals(o)) { System.out.println("C"); } else { System.out.println("D"); } // Which labels are printed among A B C D?
-
A1 and 3
-
B2 and 4
-
C3 and 4
-
D1 and 2
-
E2 and 3
Answer
Correct Answer: 1 and 3
Explanation
Introduction / Context: This question probes the symmetry of equals between a String reference and an Object reference that points to the same String instance. In Java, String overrides Object.equals to compare contents, not identity.
Given Data / Assumptions:
- s is "hello".
- o references the exact same object as s (Object o = s).
- Two equality checks are performed: o.equals(s) and s.equals(o).
- Printing uses labels: A for the first true branch, C for the second true branch.
Concept / Approach: Because o and s refer to the same String instance, equals must be symmetric: o.equals(s) is true and s.equals(o) is also true. Both branches print the true labels (A and C). The option mapping "1 and 3" corresponds to A and C respectively.
Step-by-Step Solution: o.equals(s) → true → prints "A". s.equals(o) → true → prints "C".
Verification / Alternative check: Change o to new Object(); then o.equals(s) would be false (Object.equals is identity), but s.equals(o) would also be false because String.equals checks type/contents.
Why Other Options Are Wrong: Any option including 2 (B) or 4 (D) assumes a false branch, which does not occur with identical String references.
Common Pitfalls: Confusing == with equals; forgetting that equals should be reflexive, symmetric, and transitive.
Final Answer: 1 and 3