Swap Two Numbers using XOR in Java - The Coding Shala

Home >> Java Program >> Swap Two Numbers using XOR

 In this post, we will learn how to Swap Two Numbers using XOR and will write a Java Program for the same.

Java Program to Swap Two Numbers using XOR

Swap two numbers without using an additional variable.

Example:
Input: a = 10;
          b = 20;
Output: a = 20;
             b = 10;

We can use XOR to swap the numbers.

Java Program: 

public class SwapTwoNumbers {
	public static void main(String[] args) {
		int a = 10;
		int b = 20;
		System.out.println("Before swap");
		System.out.println("a: " + a);
		System.out.println("b: " + b);
		
		//swap using xor
		a = a ^ b;
		b = a ^ b;
		a = a ^ b;
		
		System.out.println("After swap");
		System.out.println("a: " + a);
		System.out.println("b: " + b);
	}
}

Output: 

Before swap
a: 10
b: 20
After swap
a: 20
b: 10


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

Anti Diagonals - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala

Java Method Overloading - The Coding Shala