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

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

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

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala