This post will discuss how to pass integer by reference in Java.

We know that in C, we can pass arguments by reference using pointers, and the same can be done in C++ using references.

Java is pass by value, and it is not possible to pass primitives by reference in Java. Also, the Integer class is immutable in Java, and Java objects are references that are passed by value. So an Integer object points to the exact same object as in the caller, but no changes can be made to the object, which is reflected in the caller function.

1. Create custom wrapper class

Here, the idea is to wrap an integer value in a mutable object. We can do this by simply creating a reference class that contains the primitive as a member field. This is demonstrated below:

Download  Run Code

Output:

10

2. Wrapping primitive value in an array

We can also use an array of length one to wrap a primitive.

Download  Run Code

Output:

11

3. Using AtomicInteger

Alternately, we can replace primitive integer with AtomicInteger object, a built-in Java class included in the package java.util.concurrent.atomic, along with several other classes that support lock-free thread-safe programming on single variables. Note that in a single-threaded environment, this can impact performance.

Download  Run Code

Output:

10

4. Using Apache Commons Lang

Finally, we can also use the MutableInt class from the Apache Commons library. It is defined in the package org.apache.commons.lang3.mutable.

Download Code

Output:

6

That’s all about passing an integer by reference in Java.