Java (reference vs value equality) — which three comparisons evaluate to true for the given arrays and primitives?\n\n/* Options to judge: \n1) f1 == f2\n2) f1 == f3\n3) f2 == f1[1]\n4) x == f1[0]\n5) f == f1[0]\n*/\n\nimport java.awt.Button;\nclass CompareReference \n{\n public static void main(String [] args) \n {\n float f = 42.0f;\n float[] f1 = new float[2];\n float[] f2 = new float[2];\n float[] f3 = f1;\n long x = 42;\n f1[0] = 42.0f;\n }\n}\n\nSelect the set that lists all and only the true statements.

Difficulty: Medium

Correct Answer: 2, 4 and 5

Explanation:


Introduction / Context:
This problem distinguishes reference comparison for arrays from numeric comparison for primitives (with widening conversions). It asks you to evaluate five boolean expressions concerning float arrays, a copied reference, and primitive values.



Given Data / Assumptions:

  • f1 and f2 are two distinct float[] objects of the same length.
  • f3 references the exact same array object as f1.
  • f1[0] is assigned 42.0f; x is a long with value 42; f is a float with value 42.0f.
  • Comparisons use Java’s == operator semantics for references and primitives.


Concept / Approach:
For arrays, == compares object identity (same reference), not contents. For primitives, == compares numeric values after standard promotions (e.g., long with float). A comparison between a reference type and a primitive is a compile-time error.



Step-by-Step Solution:

1) f1 == f2 → false (different array objects).2) f1 == f3 → true (same object identity).3) f2 == f1[1] → invalid types (array vs float) so not true.4) x == f1[0] → 42L promoted to float 42.0f; 42.0f == 42.0f → true.5) f == f1[0] → 42.0f == 42.0f → true.


Verification / Alternative check:
Printing System.out.println(f1 == f3) yields true; modifying f1[0] is visible via f3 due to shared identity. Numeric comparisons align with Java promotion rules.



Why Other Options Are Wrong:

  • Sets including 1: reject; 1 is false.
  • Sets including 3: reject; 3 is not a legal true expression and cannot evaluate to true.


Common Pitfalls:
Assuming arrays are compared by contents with == (use Arrays.equals for that), and overlooking compile-time type errors in mixed comparisons.



Final Answer:
2, 4 and 5

Discussion & Comments

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