This post 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() method 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 the value of variable a to variable b after passing variable b to the swap() method. Then we simply return b from the swap() method, which gets assigned 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() method 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 the only reference to the object is 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. The following 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 the primitive integer by java.util.concurrent.atomic.AtomicInteger object. This is demonstrated below:

Download  Run Code

Output:

a = 10, b = 5

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

5. Swapping List

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

Download  Run Code

Output:

[1, 2, 4, 3, 5]

That’s all about swapping primitives and objects in Java.