Swap two variables in one line in Java



In order to swap two variable using single expression or in single line we could use bitwise XOR operator of Java.

As we now that in Java XOR functions as XOR of two numbers a and b returns a number which has all the bits as 1 wherever bits of a and b differs.

So for swapping of two variable we would use this operator as

Example

Live Demo

public class SwapUsingBitwise {
   public static void main(String[] args) {
      int a = 8 ; int b = 10;
      System.out.println("Before swaping : a = " + a + " b = "+b);
      a = a^b^(b = a);
      System.out.println("After swaping : a = "+ a + " b = "  + b);
   }
}

Output

Before swaping : a = 8 b = 10
After swaping : a = 10 b = 8

Advertisements