Swap two variables in one line in using Java


Two variables can be swapped in one line in Java. This is done by using the given statement.

x = x ^ y ^ (y = x);

where x and y are the 2 variables.

A program that demonstrates this is given as follows −

Example

Live Demo

public class Example {
   public static void main (String[] args) {
      int x = 12, y = 25;
      System.out.println("Original values of x and y");
      System.out.println("x = " + x);
      System.out.println("y = " + y);
      x = x ^ y ^ (y = x);
      System.out.println("Swapped values of x and y");
      System.out.println("x = " + x);
      System.out.println("y = " + y);
   }
}

Output

Original values of x and y
x = 12
y = 25
Swapped values of x and y
x = 25
y = 12

Now let us understand the above program.

First, the original values of x and y are printed. The code snippet that demonstrates this is given as follows.

int x = 12, y = 25;
System.out.println("Original values of x and y");
System.out.println("x = " + x);
System.out.println("y = " + y);

The x and y are swapped in a single line. Finally, the swapped values of x and y are displayed. The code snippet that demonstrates this is given as follows.

x = x ^ y ^ (y = x);
System.out.println("Swapped values of x and y");
System.out.println("x = " + x);
System.out.println("y = " + y);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements