Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Best way to pass int by reference

People also ask

Can we just cast the reference to an int?

You're not casting to an int, no Object can ever be cast to an int.

Does Java pass by reference or by value?

Java is officially always pass-by-value. The question is, then, “what is passed by value?” As we have said in class, the actual “value” of any variable on the stack is the actual value for primitive types (int, float, double, etc) or the reference for reference types.

Does Java pass primitive by reference?

In Java, it is not possible to pass primitives by reference. To emulate this, you must pass a reference to an instance of a mutable wrapper class.


You can try using org.apache.commons.lang.mutable.MutableInt from Apache Commons library. There is no direct way of doing this in the language itself.


This isn't possible in Java. As you've suggested one way is to pass an int[]. Another would be do have a little class e.g. IntHolder that wrapped an int.


You cannot pass arguments by reference in Java.

What you can do is wrap your integer value in a mutable object. Using Apache Commons' MutableInt is a good option. Another, slightly more obfuscated way, is to use an int[] like you suggested. I wouldn't use it as it is unclear as to why you are wrapping an int in a single-celled array.

Note that java.lang.Integer is immutable.


You can use java.util.concurrent.atomic.AtomicInteger.


Wrap the byte buffer and index into a ByteBuffer object. A ByteBuffer encapsulates the concept of a buffer+position and allows you to read and write from the indexed position, which it updates as you go along.