Everything in Java is passed by value. In this first
method
public void first()
{
int i = 5;
Value v = new Value();
v.i = 25;
second(v, i);
System.out.println(v.i);
}
you pass the value of the reference stored in v
(which points to a Value
object with an i
field with value 15
) to second
.
public void second(Value v, int i)
{
i = 0;
v.i = 20;
Value val = new Value();
v = val;
System.out.println(v.i + " " + i);
}
It dereferences the reference value to find a Value
object and changes its i
field value to 20
. You then create a new Value
object with its i
field value initialized to 15. That's what you're printing
15 0
The method returns and first
prints the value of the object the local variable v
is referencing, ie.
20