Why does this work, displaying array
in sorted order?:
Integer[] array={7,5,9,3,6,0,2,4};
MergeSort.mergeSort(array,0,7);
System.out.println(Arrays.toString(array));
Specifically, why does passing array
to a public static void method mergeSort
end up modifying the array itself? I thought that Java protected from this. For example this code:
public static void main(String[] args){
int c=2;
change(c);
System.out.print(c);
}
public static void change(int c){
c=4;
}
returns 2 instead of 4. I am confused why Java allows you to modify an array passed as a parameter, but not an int
Because Java is pass by value, and when you pass an Object
(and array is an Object
) you pass the value of the reference to the Object
. In contrast, a primitive has no reference so you just pass the value.
Edit
Similarly, you could have used the built in Arrays.sort()
method to sort your array. Java arrays are not primitive types. In Java, the primitive wrapper types are immutable (like String
). Consider,
private static void change(String in) {
in = in + " World"; // <-- modifies in here, can't change caller's reference.
}
private static void change(StringBuilder in) {
in.append(" World"); // <-- uses reference from caller.
}
public static void main(String[] args) {
String str = "Hello";
StringBuilder sb = new StringBuilder(str);
change(str);
change(sb);
System.out.println("one: " + str);
System.out.println("two: " + sb);
}