public class TestArray {
public static void main(String[] args) {
int[] ar = {1,2,3,4,5,6,7,8,9};
shiftRight(ar);
for (int i = 0; i < ar.length; i++) {
System.out.print(ar[i]);
}
// prints: 912345678 -- good
System.out.println();
reverseArray(ar);
for (int i = 0; i < ar.length; i++) {
System.out.println(ar[i]);
}
// prints: 91234567 -- I don't understand
System.out.println();
}
public static void shiftRight(int[] ar) {
int temp = ar[ar.length - 1];
for (int i = ar.length - 1; i > 0; i--) {
ar[i] = ar[i - 1];
}
ar[0] = temp;
}
public static void reverseArray(int[] ar) {
int[] temp = new int[ar.length];
for (int i = 0, j = temp.length - 1; i < ar.length; i++, j--) {
temp[i] = ar[j];
}
ar = temp;
for (int i = 0; i < ar.length; i++) {
System.out.print(ar[i]);
}
// prints: 876543219
System.out.println();
}
}
Passing an array to a parameter results in passing the reference to the array to the parameter; if an array parameter is changed within the method, that change will be visible outside of the method.
The first method, shiftRight
, does what I expect it to: it changes the array outside of the method.
The second method, however, does not change the array outside of the method. But running the for loop inside of the method prints the correct values. Why isn't the reference of ar
pointed to temp
? Is it because the variable temp
is destroyed when the method stops--does that kill the reference as well? Even if this is the case, why does Java take ar
, which was pointed to the reference of temp
and then reapply it the the original reference of ar
?
Thank you.