2

I am doing my homework but I find it has problem here:

public static void test(int[] a){

    for(int i = 0; i < a.length;i++){
        a[i] = i;
    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    int [] ints = {1,1,3,3,1,1,2,2,34,4,5,56};
    test(ints);
    for(int i = 0; i < ints.length;i++){
        System.out.print(ints[i] + " ");
    }
}

In this case, system will print out: 0 1 2 3 4 5 6 7 8 9 10 11

But When I change the test method to

public static void test(int[] a){


      int [] a2 = {2,2,2,2,2,1,2,2,34,4,5,56};
        a = a2;

}

main method system will print: 1 1 3 3 1 1 2 2 34 4 5 56
which seems like this array are not changed. Why this happen? I know maybe this is something called pass by value or reference. But I am still confusing about it.

Calvin.Xie
  • 77
  • 1
  • 1
  • 8

0 Answers0