Sunday, July 11, 2010

Swapping object in java

In java, when you are trying to swap two objects, it cannot be swapped by creating a temporary variable in a different method as given below.

public static void main (String[] arg){
    //creating two objectsto be swapped
    ClassA a1 = new ClassA();
    ClassA b1 = new ClassA();
.....
    swap(a1,b1);
}
public void swap(ClassA a, ClassA b){
    ClassA temp = a;
    a=b;
    b=temp;
}

One line answer to why objects will not get swapped is that java is a pass by value.

Basically, when we call swap method, we are passing memory location of the two objects contained in reference variables a1 and b1. So in swap method for reference variable a and b values get swapped but those will not be reflected in the reference variables a1 and b1. Instead if we have changed some property of the object that would have been reflected.

No comments:

Post a Comment