Multiple choice technology programming languages

Given the following code, what will be the output? class Value { public int i = 15; } public class Test { public static void main(String argv[]) { Test t = new Test(); t.first(); } public void first() { int i = 5; Value v = new Value(); v.i = 25; second(v, i); System.out.println(v.i); } public void second(Value v, int i) { i = 0; v.i = 20; Value val = new Value(); v = val; System.out.println(v.i + " " + i); } }

  1. 15 0 20

  2. 15 0 15

  3. 20 0 20

  4. 0 15 20

Reveal answer Fill a bubble to check yourself
A Correct answer
Explanation

Java passes object references by value. In second(), the local parameter 'v' is reassigned to a new Value object (v = val), which doesn't affect the original reference in first(). However, before reassignment, v.i = 20 modifies the object's field through the original reference. The second() method prints '15 0' (val.i=15, local i=0). Back in first(), v.i is 20 (modified by second() before reassignment), so it prints '20'. Final output: '15 0 20'. The reassignment in second() doesn't affect first()'s reference.

AI explanation

Trace it through: in first(), v.i is set to 25 on a Value object, and i=5 (a primitive, passed by value). Calling second(v, i) passes a copy of the reference v (still pointing to the same object) and a copy of i. Inside second(): i=0 only changes the local copy (caller's i is untouched); v.i=20 mutates the shared object's field via the shared reference, so the original object's i becomes 20; then a brand-new Value (val, with default i=15) is created and v is reassigned to point to val — this only rebinds second's local variable, not first's v. The print inside second() then shows val.i and local i: '15 0'. Back in first(), v still refers to the original object (i=20 from the earlier mutation), so the final println outputs '20'. Combined: '15 0' then '20', matching the marked answer.