In Java, what is the output of this program showing array reference semantics (method modifies the same array)? class PassA { public static void main(String [] args) { PassA p = new PassA(); p.start(); } void start() { long[] a1 = {3, 4, 5}; long[] a2 = fix(a1); System.out.print(a1[0] + a1[1] + a1[2] + " "); System.out.println(a2[0] + a2[1] + a2[2]); } long[] fix(long[] a3) { a3[1] = 7; return a3; } }

Difficulty: Medium

Correct Answer: 15 15

Explanation:


Introduction / Context:
This program demonstrates that arrays are objects in Java, and references to the same array point to the same underlying storage. Modifying the array via one reference is visible through all references to that array.



Given Data / Assumptions:

  • a1 initially contains {3, 4, 5}.
  • fix receives the same array reference and sets a3[1] = 7.
  • a2 receives the returned reference (the same array).
  • Prints sums of elements using a1 and a2.


Concept / Approach:
Java passes references by value. The parameter a3 points to the same array object as a1 does. Therefore the in-place update a3[1] = 7 mutates a1 as well. Both a1 and a2 refer to the same modified array.



Step-by-Step Solution:

Before fix: a1 = {3, 4, 5}.In fix: a3[1] = 7 → array becomes {3, 7, 5}. Return the same reference.Back in start: a2 points to that same array.Sum via a1: 3 + 7 + 5 = 15. Sum via a2: 3 + 7 + 5 = 15.


Verification / Alternative check:
Printing a1 == a2 yields true (same reference). Printing Arrays.toString(a1) after fix shows [3, 7, 5].



Why Other Options Are Wrong:
They either treat prints as element-by-element strings or assume the array did not mutate.



Common Pitfalls:
Confusing pass-by-value of the reference with copying the array; forgetting that arithmetic here is numeric addition, not concatenation.



Final Answer:
15 15

More Questions from Operators and Assignments

Discussion & Comments

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