How to swap two Integers without using a temporary variable in Java?
Published: 2021-07-26 07:04:32

One of the oldest trick questions from a programming interview is, How do you swap two integers without using a temp variable? This was first asked to me on a C/C++ interview and then several times on various Java interviews. The beauty of this question lies both in the trick to thinking about how you can swap two numbers without the third variable, but also problems associated with each approach. If a programmer can think about integer overflow and consider that in its solution then it creates a very good impression in the eye of interviewers.

Ok, so let's come to the point, suppose you have two integers i = 10 and j = 20, how will you swap them without using any variable so that j = 10 and i = 20? Though this is journal problem and solution work more or less in every other programming language, you need to do this using Java programming constructs.

 You can swap numbers by performing some mathematical operations like addition and subtraction and multiplication and division, but they face the problem of integer overflow.

There is a neat trick of swapping numbers using the XOR bitwise operator which proves to be the ultimate solution. We will explore and understand each of these three solutions in detail here, and if you are hungry for more programming questions and solutions, you can always take a look at Grokking the Coding Interview: Patterns for Coding Questions, one of the best course to prepare for programming job interviews.

This is not like a typical coding problem course. In this course, you will learn about 15 popular coding patterns like two-pointer, fast and slow pointer, sliding window etch which can help you to solve 100+ Leetcode problems. They are great to develop the coding sense and pattern recognition skills required to solve unknown coding problems during real Codin interviews.




2 Ways to swap two integers without using a temp variable in Java
Now that you are familiar with the problem let's talk about the solution. There are two main ways to solve this problem one using arithmetic operators and others using a bitwise operator. There are some loopholes in the first solution like overflow which can also get you some brownie points if you can bring them during interviews.

Solution 1 - Using Addition and Subtraction
You can use the + and - operator in Java to swap two integers as shown below :
a = a + b;
b = a - b;   // actually (a + b) - (b), so now b is equal to a
a = a - b;   // (a + b) -(a), now a is equal to b

You can see that it's a really nice trick and the first time it took some time to think about this approach. I was really happy to even think about this solution because it's neat, but happiness was short-lived because the interviewer said that it will not work in all conditions. 

He said that the integer will overflow if the addition is more than the maximum value of int primitive as defined by Integer.MAX_VALUE and if subtraction is less than the minimum value, I mean Integer.MIN_VALUE.

It confused me and I conceded only to find that the code is absolutely fine and works perfectly in Java because overflows are clearly defined. And, Yes, the same solution will not work in C or C++ but it will work absolutely fine in Java.

Don't believe me? here is the proof :

a = Integer.MAX_VALUE;
b = 10;

System.out.printf("Before swap 'a': %d, 'b': %d %n", a, b);

a = (a + b) - (b = a);

System.out.printf("After swapping, 'a': %d, 'b': %d %n", a, b);

Output :
Before swap 'a': 2147483647, 'b': 10 
After swapping, 'a': 10, 'b': 2147483647 

Here the addition of two numbers will overflow, Integer.MAX_VALUE + 10 = -2147483639, but we are also doing subtraction, which will compensate this value because b is now Integer.MAX_VALUE and -2147483639 - 2147483647 will again overflow to give you 10 as output.

If you are not familiar with different data types, both primitives and wrapper classes and want to know more about their limitations and how they work then I suggest you join a comprehensive Java course like The Complete Java Masterclass by Tim Buchalak and his team on Udemy.

This covers all basic including bitwise operators which we will see in the next section and it is also the most up-to-date course. You can buy in just $9.99 on crazy Udemy sales which happen every now and then.

How to swap two Integers without using additional variable?

Btw, it's a lot easier to solve this problem and swap variables in Python, so its highly unlikely that you will get this problem during a Python interview :-)


Solution 2 - Using XOR trick
The second solution to swap two integer numbers in Java without using the temp variable is widely recognized as the best solution, as it will also work in a language that doesn't handle integer overflows like Java, for example,  C and C++. Java provides several bitwise and bitshift operators, one of them is XOR which is denoted by ^.

If you remember the XOR truth table then you know that A XOR B will return 1 if A and B are different and 0 if A and B are the same. This property gives birth to the following code, popularly known as the XOR trick:

x = x ^ y;
y = x ^ y;   // now y = x
x = x ^ y;  // now x = y

Here is an example of swapping two numbers using the XOR bitwise operator in Java, you can see that values of X and Y are swapped after the third operation.

And, if you want to learn more about Bitwise operators in Java and Programming in general,  I highly recommend you read the Hackers Delight by Henry S. Warren book, its the bible to learn about bitwise and bitshift operation and reverted by expert programmers.