How to swap two Integers without using a temporary variable in Java? [Solution] (original) (raw)

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 Coding 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 Buchalaka 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.

How to swap two numbers without using temporary variable in Java?

Java Program to Swap Two Integers without a temporary variable

In this Java program, I will show you a couple of ways to swap two integers without using any temporary or third variable, and what problems come with each approach, and which one will work in all conditions.

Actually, the two popular solution works perfectly fine in Java but candidates, especially those coming from C and C++ background often think that first solution is broken and will fail on integer boundaries, but that's not true.

Integer overflows are clearly defined in Java, like Integer.MAX_VALUE + 1 will result in Integer.MIN_VALUE, which means if you do both addition and subtraction with the same set of numbers, your result will be fine, as seen in the above example.

/**

}

Output One way to swap two numbers without temp variable Before swap 'a': 10, 'b': 20 After swapping, 'a': 20, 'b': 10 Before swap 'a': -2147483648, 'b': 2147483647 After swapping, 'a': 2147483647, 'b': -2147483648 Swap two integers without third variable using XOR bitwise Operator Before swap 'x': 30, 'y': 60 After swapping, 'x': 60, 'y': 30

That's all about how to swap two integers without using a temporary variable in Java. Unlike popular belief that the first solution will not work on integer boundaries i.e. around maximum and minimum values, which is also true for languages like C and C++, it works perfectly fine in Java.

Why? because overflow is clearly defined and addition and subtraction together negate the effect of overflow.

There is no doubt about the second solution as it is the best solution and not subject to any sign or overflow problem. It is also believed to be the fastest way to swap two numbers without using a temp variable in Java.

And how about this meme :)

How to swap two Integers without using temporary variable in Java?

Anyway, If you are preparing for programming job interviews and looking for some good resources, then you can also take help from the following books and courses, the best resources of programming questions, and brushing up your Data Structure and Algorithms skills. :

If you are interested in solving some simple and some tricky programming questions, I suggest you take a look at the following set of programming problems :

Thanks for reading this article so far. If you like this interview question then please share it with your friends and colleagues.

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Data Structure in Java free course on Udemy. It's completely free and all you need to do is create a free Udemy account to enroll in this course.