Java Program to Swap Two Numbers Without Using Third Variable

Here you will get java program to swap two numbers without using third variable or temporary variable.

We can do this in 3 ways as mentioned below.

Also Read: Java Program to Swap Two Numbers Using Temporary Variable

 

1. Using Addition & Subtraction Operator

We can swap two numbers using addition (+) and subtraction (-) operator.

public class JavaSwapNumbers {
	public static void main(String args[]){
		int a = 5, b = 6;
		
		System.out.print("Before swap:\na = " + a + "\nb = " + b);
		
		a = a + b;	//a becomes 11
		b = a - b;	//b becomes 5
		a = a - b;	//a becomes 6
		
		System.out.print("\n\nAfter swap:\na = " + a + "\nb = " + b);
	}
}

Output

Before swap:
a = 5
b = 6

After swap:
a = 6
b = 5

 

2. Using Multiplication & Division Operator

We can swap two numbers using multiplication (*) and division (/) operator.

public class JavaSwapNumbers {
	public static void main(String args[]){
		int a = 5, b = 6;
		
		System.out.print("Before swap:\na = " + a + "\nb = " + b);
		
		a = a * b;	//a becomes 30
		b = a / b;	//b becomes 5
		a = a / b;	//a becomes 6
		
		System.out.print("\n\nAfter swap:\na = " + a + "\nb = " + b);
	}
}

 

3. Using Bitwise XOR Operator

We can also swap two numbers using bitwise XOR (^) operator. This operator does xor of bits in binary representation of numbers. See below example.

public class JavaSwapNumbers {
	public static void main(String args[]){
		int a = 5, b = 6;	//a is 101 and b is 110
		
		System.out.print("Before swap:\na = " + a + "\nb = " + b);
		
		a = a ^ b;	//a becomes 3 (011)
		b = a ^ b;	//b becomes 5 (101)
		a = a ^ b;	//a becomes 6 (110)
		
		System.out.print("\n\nAfter swap:\na = " + a + "\nb = " + b);
	}
}

 

Comment below if you know any other way to swap two numbers in java without using third or temporary variable.

 

Leave a Comment

Your email address will not be published. Required fields are marked *