One of the favorite basic questions asked by the interviewers:

Q. Write a function to swap two integers?

A “C” programmer will write function similar to .


void swap(int *a, int *b){
   int temp = *a;
   *a=*b;
   *b=temp;
}

But what if you are asked to implement the same method in Java, then you will answer that pointer concept doesn’t exist in Java. Everything in Java is reference. And int is primitive type in java. Some of the people may suggest to use the Integer object to achieve it and write the following code:

public static void main(String[] args) {

   Integer a = 10;
   Integer b = 20;
   swap(a, b);
   System.out.println("a : " + a + ", b : " + b);
}
public static void swap(Integer aArg, Integer bArg){
   Integer temp = aArg;
   aArg = bArg;
   bArg = temp;
}

Those people, who know java Integer class, will not agree for this solution. They will argue that Integer is immutable class and once its value is initialized,  the value can’t be changed. Well, this is correct. If you execute this method, you will not see the expected result. Let’s analyze this method and find out what is going wrong  The above java code is equivalent to the “C” code given below. If you are a ‘C’ programmer, then you may have noticed that the pointers’ value(address pointed by the pointer) is being changed rather than the value stored at that address.

void swap(int *a, int *b){
   int  *temp = a;
   a = b;
   b = temp;
}

Similar behavior is exhibited by the Java version of swap() method. If you don’t trust me, then try eclipse in debug mode. You will notice that  Integer objects that passed have unique Id associated with it. In other words, Id can be assumed as a kind of address assigned to object. The arguments received in the method argument Integer object aArg and bArg have the corresponding Ids as shown in the Fig.1 below. When the method is executed, the Ids associated with aArg and bArg get swapped which means that they have started pointing to the others’ object rather than changing their object’s value.

Integer swap in java

Some developers may suggest to use the getter and setter method to swap the values but Integer class is a immutable class. It doesn’t have setter method.  Once the Integer object is initialized, object can’t change its value. If you already aware of all these concepts, then you may also have solution for this problem. Promptly you will suggest to implement a mutable wrapper class which has getter and setter methods (similar to the example given below).

public class IntWrapper {
	 private int value;
	 public IntWrapper(int value){
		 this.value = value;
	 }
	 public int get(){
		 return this.value;
	 }
	 public void set(int value){
		 this.value = value;
	 }
 }
public void swap(IntWrapper aArg , IntWrapper bArg){
	IntWrapper temp = new IntWrapper(aArg.get());
	aArg.set(bArg.get());
	bArg.set(temp.get());
}

Well, this code will certainly work. But what if I ask you to only use Integer class object and not the wrapper clas ? You will definitely argue that I am contradicting myself and it can not be done in java(remember Integer is immutable class). I would say that there is a sneaky way to swap the value of Integer object and also have bad repercussion on the JVM. If you are a geeky person or know Reflection in Java, then you may have understood my hint. we can modify the accessibility of the variable with the help of reflection and change the object property. The Integer class stores the value in “value” member variable which is private final variable. In the swap() method, we get the value field from Integer class and set the accessibility to true. It allows us to change the object value. In the next few lines, the value of objects is getting swapped.

  public static void main(String[] args) {
		IntegerSwap is = new IntegerSwap();
		Integer a = 10;
		Integer b = 20;
		is.swap(a, b);
		System.out.println("a : " + a +", b : " + b);
	}
 public void swap(Integer aArg , Integer bArg){
	try {
		Field valueField = Integer.class.getDeclaredField("value");
		valueField.setAccessible(true);
		int temp = aArg;
		valueField.setInt(aArg, valueField.getInt(bArg));
		valueField.setInt(bArg,temp);
                valueField.setAccessible(false);
	} catch (Exception e) {
		System.err.println(e.getMessage());
	}
}

There is a problem with this solution. If you have identified the problem then I can assert that you have a good knowledge of Java and JVM. If you haven’t figured out the problem, then you need to know more about the JVM. Integers obtained via Integer.valueOf() and between -128 and 127 are cached for the whole JVM. Changing the value will change the value everywhere in the running JVM. You can explore the Integer class source code here. The above reflection solution is just a hack. It shouldn’t be used in the real world scenario.

Note: Reflection is two edged sword, it should be used with caution.

If you know any smart and safe way of swapping Integer value, then please share it in the comment section.

Please feel free to comment on the blog or website.

, ,
Trackback

6 comments untill now

  1. nice article rakesh.

    Thanks
    Prasanth Jalasutram

  2. Don’t forget that Integers obtained via Integer.valueOf() and between -128 and 127 are cached for the whole JVM!!! Swapping one of these will replace its value everywhere in the runnning JVM.

  3. @John
    Thanks for pointing out the issue. I am going to update the post.

  4. This might be a nice addition as a warning to your article ;-)
    http://thedailywtf.com/Articles/Disgruntled-Bomb-Java-Edition.aspx

  5. If reflection is a dirty way of doing swapping variables, is the wrapper way the only legal way?

  6. @Prasad, Wrapper class does work.
    But in an interview it completely depends on the interview what kind of answer he is looking for. Best to explain your answer and give reasons behind the solution.

Add your comment now