How to pass integer by reference in Java

In this post, we will see how to pass integer by reference in Java.


 

We know that in C, we can pass arguments by reference using pointers, and 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 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 and but no changes can be made to the object which gets reflected in the caller function.

 

1. Create custom wrapper class

The idea here is to wrap an integer value in a mutable object. This can be done by simply creating a reference class that contains the primitive as a member field. This is illustrated 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 by AtomicInteger object which is 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:

11

 

4. Apache Commons MutableInt class

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

 

Download   Run Code

Output:

6

 
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