Swapping primitives and objects in Java

In this post, we will discuss how to swap primitives and objects in Java.


 

We know that the most common solution to swap two integers in C/C++ is to create a utility swap() function using pointers in C or references in C++ as shown below:

 

 
This won’t work in Java since Java is pass by value and it is not possible to create a method for swapping two primitives in Java. This post discusses some of the workarounds/tricks for swapping integers in Java.

 

1. Swapping primitives

Here’s one plausible way of swapping two integers (say a and b) in Java. The idea is to assign value of variable a to variable b after passing variable b to the swap() function. Then we simply return b from the swap() function which gets assign to a inside the calling method.

 

Download   Run Code

Output:

a = 10, b = 5

 

2. Swapping array elements

If values to be swapped are elements of an array, we can easily write a swap() function by passing the array indices, instead of the actual elements as shown below:

 

Download   Run Code

Output:

[1, 2, 4, 3, 5]

 

3. Swapping Objects

We know that Java objects are references that are passed by value. That means only reference to the object are copied and the object points to the exact same object as in the caller and any changes made to the object will be reflected in the caller function. Below code does that by wrapping the integer value in a mutable object.

 

Download   Run Code

Output:

a = 10, b = 5

 

4. Swapping AtomicInteger

Alternately, we can replace primitive integer by java.util.concurrent.atomic.AtomicInteger object. This is illustrated below:

 

Download   Run Code

Output:

a = 10, b = 5

 
We can replace AtomicInteger class by org.apache.commons.lang.mutable.MutableInt class from Apache Commons library.

 

5. Swapping List

Finally if we need to swap two elements of a list, we can just call Collections.swap() method which swaps the elements at the specified positions in the specified list.

 

Download   Run Code

Output:

[1, 2, 4, 3, 5]

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of