-1

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?

2 Answers2

2

In Java - "References to Objects are passed by value".

public class Swap {
    public static void swap(int[] a){  // now a = x --> {5,3}
        int temp = a[1]; 
        a[1] = a[0];     // swapping a[0] and a[1] in this and next step.
        a[0] = temp;
// NOW only a[] goes out of scope but since both x and a were pointing to the "same" object {5,3}, the changes made by a will be reflected in x i.e, in the main method.
    }

    public static void main(String[] args){
        int[] x = {5,3}; // here - x is a reference that points to an array {5,3}
        swap(x);   
        System.out.println("x[0]:" + x[0] + " x[1]:" + x[1]);
    }
}

And,

public class Switch {
    public static void switch(String s){ // now s=x="Hello"
        s = "GOODBYE";   //here x="hello" , s ="GOODBYE"  i.e, you are changing "s" to point to a different String i.e, "GOODBYE", but "x" still points to "Hello"
    }
    public static void main(String[] args){
        String x = "HELLO";
        switch(x);
        System.out.println(x);
    }
}
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
2

Because writing s = "GOODBYE"; just points s to a different String. It doesn't change the value of the original String.

Whereas writing a[0] = something; or a[1] = something; is actually messing around with the array referenced by a, but not pointing a to a different array.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110