user3313599
user3313599

Reputation: 1

Aliasing in objects

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() + " ");
    }

}

Upvotes: 0

Views: 159

Answers (1)

Shirish Mishra
Shirish Mishra

Reputation: 61

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.

Upvotes: 1

Related Questions