0

I wonder why the output is still 1,2,3,4,5, since if I change a value in doIt (for example : z[0] = 10), the array is changed.

public class Main 
{
    public static void main(String[] args) {
        int[] array = {0,1,2,3,4,5};
        testIt.doIt(array);

        for(int i=0;i<array.length;i++){
            System.out.println(array[i]);
        }
    }
}

class testIt
{
    public static void doIt(int [] z){
        z = null    
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
David
  • 840
  • 6
  • 17
  • 37
  • 1
    Read this http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value/40523#40523 – René Link Oct 22 '14 at 06:39

2 Answers2

1

doIt is passed a copy of the array reference, so it can't change the original reference (stored in the array variable). It can only change the state of the object referred by this reference. Therefore setting z to null inside doIt makes no difference outside the method.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

Here

doIt is passed a copy of the array reference and can't change the original reference and make no difference to original array.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115