-2

So I've got this piece of code,

package test1;
class Student13
{
    public static void main(String [] args) 
    {
        Student13 p = new Student13();
        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;
    } 
}

Can you tell me why it returns 15 15 and not 12 15? Function fix is applied only for long[] a2, so how come that the final result is 15 15?

Captain Man
  • 6,997
  • 6
  • 48
  • 74
stack404
  • 15
  • 5

3 Answers3

1

You pass the a1 array to fix(), which is called a3 in the fix() method, but is regardless still referencing a1. So when you update a3: a3[1]=7, you actually update the paramater value of fix() which was a1. Thus you updated a1!

Roel Strolenberg
  • 2,922
  • 1
  • 15
  • 29
1

In the line

long a1[] = { ... };

you are creating one array object. This will be the only one throughout the rest of the program.

Now the call to

fix(a1);

assigns a reference to exactly that array to the parameter a3 in this fix method. As this method returns this reference (return a3;), the line

long[] a2 = fix(a1);

will assign the same reference to the variable a2. So at all points, all variables and parameters referred to the same array.

The fix method is modifying that array. So the modification is seen by all aliases you have.

Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66
0

Reference of a1[] is passed as a parameter to fix() that's why basically

a1[] == a2[] after calling fix().

a2[] is pointing to a1[] but a1[] sum is now 15, so a2[] sum is also 15.

Rey Libutan
  • 5,226
  • 9
  • 42
  • 73