0

When running the function foo1, why does the output for this code will be: 15 30 5 and not 15 15 5 ?

I underdtand that the pointer of the object v is now points to the object va1, so the output for the code line: System.out.print(v.getI() + " "); should be 15. So why is it 30 ?

public class Value
{
    private int _i;

    public Value()
    {
        _i=15;
    }

    public int getI()
    {
        return _i;
    }

    public void setI (int i)
    {
        _i=i;
    }

}

public class TestValue
{
    public static void foo1()
    {
        int i=5;
        Value v= new Value();
        v.setI(10);
        foo2(v,i);
        System.out.print(v.getI() + " ");
        System.out.print(i+ " ");

    }

    public static void foo2( Value v, int i)
    {
        v.setI(30);
        i=10;
        Value va1= new Value();
        v=va1;
        System.out.print (v.getI() + " ");
    }

}
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
  • possible duplicate of [Is Java "pass-by-reference"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference) – Radiodef Feb 16 '14 at 16:40

1 Answers1

1

Java only supports pass-by-value. So when you pass an object "v" to the method foo2 a copy of the reference "v" is created. So when you set v = val1 in foo2 the copy of the reference is being changed in foo2 not the original reference "v" in foo1.