How to swap two integer variables in Java?

Tarun Telang
1 min readJun 8, 2022
Photo by Adrià Crehuet Cano on Unsplash

Swapping two values usually requires a temporary variable to store one of the values. However, it is possible to swap two integer variables without using any additional storage. This can be done by using arithmetic operators or bitwise operators.

Temporary Variable Swap

The most common way to swap two variables is to use a temporary variable. For example, if we want to swap x and y, we would do the following:

Arithmetic Operator Swap

However, this method requires the use of an additional variable. We can also swap two variables without using a temporary variable by using arithmetic operators. For example, if we want to swap x and y, we can do the following:

Bitwise Operator Swap

It is also possible to swap two variables without using a temporary variable or arithmetic operators. This can be done by using bitwise operators. For example, if we want to swap x and y, we can do the following:

Both of these methods are efficient and do not require the use of an additional variable.

--

--

Tarun Telang
Tarun Telang

Written by Tarun Telang

Prolific Author, Engineering Leader, Software Architect

No responses yet