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.

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.

 

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.

 

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

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.