11

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);
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
sabu
  • 1,969
  • 4
  • 18
  • 28

8 Answers8

11

You studied wrong sources. Java is pass by value. Here is one source more you can study. And from here you can find discussion about example similar to yours.

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
8

1. First and foremost thing, Java is pass by Value.( ie Pass by Copy).

2. You are passing the reference Not the Object to the method.

Eg:

public class Test{

        private String x;

            public void go(String s){

                this.x = s;

           }

         public static void main(String[] args){

                  Test t = new Test();

                  String a = new String("Bye");

                  t.go(a);


             }
      }

The above code is not to show how swapping is done, but to make an important point visible.

  • When go(String s) method is called by passing an Argument "a" which is an Object reference variable of type String to the Parameter "s" which is also an Object reference variable of type String, its just the reference that is passed by Value / Copy.

  • Any changes done on the reference will effect the String object on the Heap, NOT the reference.

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • 1
    "Any changes done on the reference will effect the String object on the Heap, NOT the reference" I don't really get this statement. As opposed to what? – newacct Jul 28 '12 at 19:03
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;
}
adarshr
  • 61,315
  • 23
  • 138
  • 167
2

Java passes references by value; swapping references in the method being called has no effect in the caller. Your strings are immutable, so there is nothing you can do to them in the swap method that would be visible to the caller.

If you pass mutable objects, however, you will see that changes to them made in the swap would reflect in the original:

public static void main(String[] args) {
    String a[] = {"hello", "world"};
    swap(a);
    System.out.println(a[0] + " " + a[1]);
}
static void swap(String[] a) {
    String t = a[0];
    a[0] = a[1];
    a[1] = t;
}

This works, because array is mutable (i.e. changes can be made to its state), and because a reference to the original object is passed to the function being called (by value). When swap modifies the content of its a, the content of a in the caller gets modified too, because it is the same object.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • "If you pass mutable objects, however..." It has nothing to do with immutable or mutable objects. You can't swap references to mutable objects either. You're passing a mutable collection and asking to swap the internal elements of it, which is completely different. – newacct Jul 28 '12 at 19:01
  • 1
    @newacct If you read the entire sentence, not just the beginning, you will see that it does not mention anything about swapping references of mutable objects: it says that changes to mutable objects are reflected in the originals, even though the references are passed by value. – Sergey Kalinichenko Jul 28 '12 at 22:17
  • Okay but I also don't like this sentence: "Your strings are immutable, so swapping references to them has no effect." Swapping references to anything has no effect, and it's not because they are immutable. – newacct Jul 28 '12 at 23:02
  • @newacct I can see how that could be misleading. I edited the answer to clarify. Thanks! – Sergey Kalinichenko Jul 28 '12 at 23:07
1

Java always passes the references by value. Read this answer for more details. However, you can swap two strings via arrays or wrapper classes.


EDIT:

@dasblinkenlight shows how to use arrays to swap two strings, and here is an example of using wrapper class:

public class WrapperString
{
    public String text;

    public WrapperString(String text){this.text = text}

    @Override
    public String toString(){return text;}
}

public static void swap(WrapperString a, WrapperString b)
{
    String temp = a.text;
    a.text = b.text;
    b.text = temp;
}

public static void main(String[] args)
{
    WrapperString s1 = new WrapperString("Hello");
    WrapperString s2 = new WrapperString("World");

    swap(s1, s2);
    System.out.println(s1.text + s2.text);
    // or System.out.println(s1 + s2); since we've already overridden toString()
}

OUTPUT:

WorldHello
Community
  • 1
  • 1
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

Java is Strictly Pass by value.

Let's modify your code as below from the explanation point of view

static void swap(String str1, String str2){
String temp = str1;
str1=str2;
str2=temp;
}

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

}

S1 and S2 are the references which hold the address of the string object. For ex: S1=123 , S2= 234

When we call swap method, copy of S1 and S2 is created and will be assigned to str1 and str2.

Which will be str1=123 and str2=234.

Swap method will only swap the values present in str1 and str2. (str1=234 str2=123) whereas S1 and S2 still points to the same memory location.

This is the reason why the swap is not reflected in the main method.

S.Asha
  • 11
  • 3
0
public static void swap(SwapDate[] t)
    {
     SwapDate temp;;
      temp=t[0];
       t[0]=t[1];
       t[1]=temp;
    }




       public static void main(String args[])throws Exception{

          SwapDate t[]=new SwapDate[5];
           t[0]=new SwapDate(20,8,2015);
           t[1]=new SwapDate(8,8,2015);

           System.out.println("(First object)Account Opnening date :"+" "+t[0].date);
           System.out.println("(second object)Account Opnening date :"+" "+t[1].date);


           swap(t);
           System.out.println("After Swap");

           System.out.println("(First object)Account Opnening date :"+" "+t[0].date);
           System.out.println("(second object)Account Opnening date :"+" "+t[1].date);


           }
-2

We can swap objects. It's so simple.Just have to use one dummy object to swap two objects.

Example is given below:

    Employee e1=new Employee();
    Employee e2=new Employee();
    e1.setName("e1");
    e2.setName("e2");   
    System.out.println(e1);
    System.out.println(e2);
    Employee temp= new Employee();
    temp=e1;
    e1=e2;
    e2=temp;
Ashish Nijai
  • 321
  • 2
  • 13