OK so I understand that Java is pass by value (including for References, it passes the Object by the VALUE of the reference - i.e. the address).
If so then why does the swap(int[] array)
method - passing an array of primitives - work?
public class TestArraySwap {
public static void swap(int a, int b) {
int temp =b;
b=a;
a=temp;
}
public static void swap(int[]a) {
int temp = a[1];
a[1]=a[0];
a[0]=temp;
}
public static void main(String[] args) {
//Test Primitive swap
int a=1;
int b=2;
System.out.println("a="+a +" b="+b);
swap(a,b);
System.out.println("a="+a +" b="+b);
//Test array swap
int[] array = new int[2];
array[0]=1;
array[1]=2;
System.out.println("a[0]="+array[0] +" a[1]="+array[1]);
swap(array);
System.out.println("a[0]="+array[0] +" a[1]="+array[1]);
}
}
The output is
a=1 b=2
a=1 b=2
a[0]=1 a[1]=2
a[0]=2 a[1]=1
The second swap works - I would expect it not to but perhaps I am missing something?