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

Longest Substring Without Repeating Characters Java Program - The Coding Shala

Anti Diagonals - The Coding Shala

First Missing Positive Solution - The Coding Shala

Shell Script to Display the digits which are at odd positions in a given 5-digit number - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala