0

Hi guys I was looking at practice problems and I really do not understand the output of this program How should I understand the reference of arrays? I realize that 1. changing the elements in z and temp (in abc method) changes the y array in the abc method 2. changing the y array in the abc method changes the z array in the abc method.

My question: why is that? How should I understand references between several arrays?

Thanks a lot!!!

    public class Test{
      public static void main (String[] args){
        int [] x = {1,2,3,4,5};
        int [] y = {7,8,9,10};
        abc (x[1], x, y);
        print (x);
        print (y);
      }

      public static void print (int [] x) {
        for (int i=0;i<x.length;i++)
          System.out.print(x[i] +  " ");
        System.out.println();
      }

      public static void abc (int x, int []y, int [] z){
        int [] temp = y;
        x += 2;
        y = z;
        z [1] += 5;
        System.out.println(x);
        z = temp;
        z[3] = 42;
        temp[2] = 100;
        z [0] = 234;
        y [1] = 4234;
      }
    }

The output:

4
234 2 100 42 5 
7 4234 9 10
husky love
  • 323
  • 1
  • 3
  • 4
  • I just do not understand the whole thing...... I add a few lines in the abc method.. and realize that changing the elements in z and temp changes the x array in the method; and changing the y array in the abc method changes the z array in the abc method. Please see the update. Thanks a lot!!! – husky love Dec 08 '15 at 02:40
  • You might also enjoy [this](http://stackoverflow.com/questions/32010172/what-is-the-difference-between-a-variable-object-and-reference). – Sotirios Delimanolis Dec 08 '15 at 02:42
  • Thanks! but I still do not understand why changing z and temp changes y but changing y actually changes z.... – husky love Dec 08 '15 at 02:46
  • Read both links more carefully. It's all there. – Sotirios Delimanolis Dec 08 '15 at 02:47

0 Answers0