swap two variables in java in single line

Let’s learn to swap two variables in java in single line.

swap two variables in java in single line

In single expression we can swap two variables or two integers. To swap two variables in one line we are using bitwise xor operator.

Bitwise xor operator of two numbers returns 1 if both bits in its operand are different else returns 0. Let’s see an example.

public class SwapTwoVariablesInOneLine
{
   public static void main(String[] args)
   {
      int x = 23;
      int y = 75;
      System.out.println("Before swapping two numbers: x = " + x + " y = " + y);
      x = x ^ y ^ (y = x);
      System.out.println("After swapping two numbers: x = " + x + " y = " + y);
   }
}


Output:

Before swapping two numbers: x = 23 y = 75
After swapping two numbers: x = 75 y = 23


Also read – abstraction in java