I just got back my Java test paper and there is one question that has been bugging me.
There was a question:
What is the output of the following program?
public class Swap {
public static void swap(int[] a){
int temp = a[1];
a[1] = a[0];
a[0] = temp;
}
public static void main(String[] args){
int[] x = {5,3};
swap(x);
System.out.println("x[0]:" + x[0] + " x[1]:" + x[1]);
}
}
The thought that first came to my mind was that this was a trick question. Since the swap method return type was void, I thought that it had no effect on the int[] x array. My answer was x[0]:5 x[1]:3. I was almost certain that I got the correct answer and when I saw that I had been marked wrong, I got confused. I went to try out the actual code on NetBeans and realized that the values in the array actually got swapped! I then went on to test if this was the case for String. I typed in a similar but different code:
public class Switch {
public static void switch(String s){
s = "GOODBYE";
}
public static void main(String[] args){
String x = "HELLO";
switch(x);
System.out.println(x);
}
}
The output still printed HELLO instead of GOODBYE. Now my question is why does the method not change the String but it changes the values inside an array?