Java reference equality and equals on the same object: compute the final result value printed.\n\npublic class ObjComp {\n public static void main(String [] args ) {\n int result = 0;\n ObjComp oc = new ObjComp();\n Object o = oc;\n if (o == oc) result = 1;\n if (o != oc) result = result + 10;\n if (o.equals(oc)) result = result + 100;\n if (oc.equals(o)) result = result + 1000;\n System.out.println("result = " + result);\n }\n}

Difficulty: Easy

Correct Answer: 1101

Explanation:


Introduction / Context:
This program compares an object reference and another reference to the same object using both identity (==, !=) and value equality (equals). Because equals inherits from Object and both references point to the same instance, all equals checks are true and identity equality is also true.


Given Data / Assumptions:

  • o and oc refer to the very same instance.
  • Object.equals defaults to identity unless overridden; here, ObjComp does not override equals.
  • We sum flags into result depending on each check’s outcome.


Concept / Approach:
Identity check: (o == oc) is true, (o != oc) is false. Equals: o.equals(oc) and oc.equals(o) both evaluate to true because both references are identical, so Object.equals returns true in both directions.


Step-by-Step Solution:
Start result = 0. (o == oc) → true → result = 1. (o != oc) → false → no change. o.equals(oc) → true → result = 1 + 100 = 101. oc.equals(o) → true → result = 101 + 1000 = 1101. Printed: "result = 1101".


Verification / Alternative check:
If o referenced a different ObjComp instance, identity would be false and equals would also be false (since equals is not overridden), yielding 0.


Why Other Options Are Wrong:
1, 10, 101 omit one or more true conditions; only 1101 includes all correct increments.


Common Pitfalls:
Assuming equals is always overridden to compare state; conflating identity and equality.


Final Answer:
1101

More Questions from Java.lang Class

Discussion & Comments

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