How to swap two variables without using extra temporary variable?

This is one of the popular interview questions. If you are given two variables and you have to swap the value of those two two variables (or array locations) without using extra memory space, how would you do that?

There are two ways of doing it:

• Using Numeric Operation (+ / -)
• Using Bitwise XOR Operation (^).

The following java program shows how this is done in Java.

package com.icodejava.blog;

import java.util.Arrays;

/**
* @author Kushal Paudyal
* www.icodejava.com
* Created On -  Mar 6, 2014
* Last Modified On - Mar 6, 2014
*/
public class InPlaceVariableSwap {

public static void main(String args[]) {
int[] data = { 5, 6 };
swapUsingNumericOperators(data);
swapUsingBitwiseOperator(data);
}

/**
* @param data
*            - sample size 2 integer array. This method will swap data
*            and data without using extra variable using numeric
*            operation.
*
*            Formula: a = b - a; b = b - a; a = a + b
*/
private static void swapUsingNumericOperators(int[] data) {
if (data == null || data.length > 2) {
return;
}
System.out.println("\nIN PLACE SWAP USING NUMERIC OPERATOR");
System.out.println("Input:" + Arrays.toString(data));

data = data - data;
data = data - data;
data = data + data;

System.out.println("Swapped:" + Arrays.toString(data));

}

/**
* @param data
*            - sample size 2 integer array. This method will swap data
*            and data without using extra variable using bitwise XOR
*            operation.
*
*            Formula: a = a ^ b; b = a ^ b; a = a ^ b
*/
private static void swapUsingBitwiseOperator(int[] data) {
if (data == null || data.length > 2) {
return;
}
System.out.println("\nIN PLACE SWAP USING BITWISE XOR OPERATOR");
System.out.println("Input:" + Arrays.toString(data));

data = data ^ data;
data = data ^ data;
data = data ^ data;
System.out.println("Swapped:" + Arrays.toString(data));

}
}

Here is the output of running the above program.

IN PLACE SWAP USING NUMERIC OPERATOR
Input:[5, 6]
Swapped:[6, 5]

IN PLACE SWAP USING BITWISE XOR OPERATOR
Input:[6, 5]
Swapped:[5, 6]

[My Video Promotion]

3 Responses to Finding Mean Value Of An Integer Array In Java

1. Jerry says:

we need the the square root of the number, not the number itself.
squareRoot = midValue * midValue;

if (squareRoot == number) {
return squareRoot;

2. Sabrina Kundu says:

Hi Kushal,

This program works for some cases, but not all. For example, 4 prints out 4.0 when it is supposed to print out 2.0. Fortunately, I found the mistake. If you change “if (squareRoot == number) return squareRoot;” to “if(squareRoot == number) return midValue;”, then the program prints out the correct square root for even numbers.

Thanks,

Sabrina

• icodejava says:

Thank you Sabrina for the feedback.

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