Alex Rivera | Logout

swapping of objects in java

Asked 2012-07-28T09:49:14.917
13

I have studied that java is pass by reference but when I execute following code the strings are not swapped in main method why?

static void swap(String s1, String s2){
    String temp = s1;
    s1=s2;
    s2=temp;
}

public static void main(String[] args) {
    String s1 = "Hello", s2 = "world";
    swap(s1, s2);
    System.out.println(s1 + s2);
}
Edit
Report

1 Answer

3

What gets passed to a method is a copy of the reference of the object. So, no matter how many times you re-assign the references, the original reference will not be affected.

Try this:

static void reverse(StringBuilder builder) {
    builder.reverse();
}

public static void main(String[] args) {
    StringBuilder builder = new StringBuilder("hello");
    System.out.println(builder);
    reverse(builder);
    System.out.println(builder);
}

However, the below method wouldn't make any difference to the original object passed in.

static void swap(StringBuilder builder) {
    builder = null;
}
answered 2012-07-28T09:51:08.293

Your Answer