Sharingan
Sharingan

Reputation: 333

JAVA Assignment & Operators

the code below is printing out 15 15, however I was expecting it to print out 12 15. It seems like the fix method is updating a1 so that it contains 3,7,5 as opposed to 3,4,5. Anyone know why this is the case?

class PassA 
{
    public static void main(String [] args) 
{
    PassA p = new PassA();
    p.start();
}

void start() 
{
    long [] a1 = {3,4,5};
    long [] a2 = fix(a1);
    System.out.print(a1[0] + a1[1] + a1[2] + " ");
    System.out.println(a2[0] + a2[1] + a2[2]);
}

long [] fix(long [] a3) 
{
    a3[1] = 7;
    return a3;
}
}

Upvotes: 0

Views: 2832

Answers (3)

Dave
Dave

Reputation: 1874

You are passing the array by reference, thats why in the fix() method, the original array gets modified. You can pass a copy to the method using

long [] a2 = fix( Arrays.copyOf(a1, a1.length));.

OK, technically, you are passing the array by value, but the value is the reference.

Upvotes: 0

Amr
Amr

Reputation: 2460

This would achieve your target 12 15

long [] fix(long [] a3) 
{
    return new long[]{a3[0], 7, a3[2]};
}

Because otherwise, you pass a1 (named as a3), modify an element, which subsequently changes it in a1. So now a1 is changed. Later on you return a1 and set it to a2.. So a2 and a1 are pointing to the same array {3,7,5}

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35577

Take a look at following

 long[] fix(long[] a3) { // a3=a1 and a1= {3,4,5}
    a3[1] = 7; // a3[1]=7 means a1[1] will become 7(a1[1]=7), now a1={3,7,5}
    return a3;// return a1
}

Upvotes: 1

Related Questions