Java Object vs String equality symmetry: given the outputs A/B/C/D, which two are printed?\n\nString s = 'hello';\nObject o = s;\nif (o.equals(s)) { System.out.println("A"); } else { System.out.println("B"); }\nif (s.equals(o)) { System.out.println("C"); } else { System.out.println("D"); }\n// Which labels are printed among A B C D?

Difficulty: Easy

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

More Questions from Java.lang Class

Discussion & Comments

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