skrtbhtngr skrtbhtngr - 1 month ago 5
Java Question

Cannot understand why this Java program produces such output

Here is the code :

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);
}
}


I cannot understand why this code prints

15 0
20


on the console.

Why is it not

15 0
15


?

Answer

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
Comments