Pass integer by reference in Java
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class IntHolder { public Integer value; IntHolder(Integer value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } } class Main { public static void modify(IntHolder i) { i.value = 10; } public static void main(String[] args) { IntHolder i = new IntHolder(2); modify(i); System.out.println(i); } } |
Output:
10
2. Wrapping primitive value in an array
We can also use an array of length one to wrap a primitive.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Main { public static void increment(int[] arr) { arr[0]++; } public static void main(String[] args) { int i = 10; int[] arr = { i }; increment(arr); System.out.println(arr[0]); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.concurrent.atomic.AtomicInteger; class Main { public static void set(AtomicInteger i) { i.set(10); } public static void main(String[] args) { AtomicInteger i = new AtomicInteger(5); set(i); System.out.println(i); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import org.apache.commons.lang3.mutable.MutableInt; class Main { public static void increment(MutableInt i) { i.increment(); } public static void main(String[] args) { MutableInt i = new MutableInt(5); increment(i); System.out.println(i); } } |
Output:
6
That’s all about passing an integer by reference in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)