How to swap or exchange objects in Java?


Java uses call by value while passing parameters to a function. To swap objects, we need to use their wrappers. See the example below −

Example

 Live Demo

public class Tester{
   public static void main(String[] args) {
      A a = new A();
      A b = new A();

      a.value = 1;
      b.value = 2;

      //swap using objects
      swap(a,b);
      System.out.println(a.value +", " + b.value);

      Wrapper wA = new Wrapper(a);
      Wrapper wB = new Wrapper(b);

      //swap using wrapper of objects
      swap(wA,wB);
      System.out.println(wA.a.value +", " + wB.a.value);
   }

   public static void swap(A a, A b){
      A temp = a;
      a = b;
      b = temp;
   }

   public static void swap(Wrapper wA, Wrapper wB){
      A temp = wA.a;
      wA.a = wB.a;
      wB.a = temp;
   }
}
class A {
   public int value;
}
class Wrapper {
   A a;
   Wrapper(A a){ this.a = a;}
}

Output

1, 2
2, 1

Updated on: 23-Jun-2020

289 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements