Swap two variables in one line in using Java

Java 8Object Oriented ProgrammingProgramming

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);
raja
Published on 05-Dec-2018 12:11:13
Advertisements