How to Pass a Primitive Data Type by Reference

How do I pass a primitive data type by reference?

There isn't a way to pass a primitive directly by reference in Java.

A workaround is to instead pass a reference to an instance of a wrapper class, which then contains the primitive as a member field. Such a wrapper class could be extremely simple to write for yourself:

public class IntRef { public int value; }

But how about some pre-built wrapper classes, so we don't have to write our own? OK:

The Apache commons-lang Mutable* classes:

Advantages: Good performance for single threaded use. Completeness.

Disadvantages: Introduces a third-party library dependency. No built-in concurrency controls.

Representative classes: MutableBoolean, MutableByte, MutableDouble, MutableFloat, MutableInt, MutableLong, MutableObject, MutableShort.

The java.util.concurrent.atomic Atomic* classes:
Advantages: Part of the standard Java (1.5+) API. Built-in concurrency controls.

Disadvantages: Small performance hit when used in a single-threaded setting. Missing direct support for some datatypes, e.g. there is no AtomicShort.

Representative classes: AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference.

Note: As user ColinD shows in his answer, AtomicReference can be used to approximate some of the missing classes, e.g. AtomicShort.

Length 1 primitive array
OscarRyz's answer demonstrates using a length 1 array to "wrap" a primitive value.

Advantages: Quick to write. Performant. No 3rd party library necessary.

Disadvantages: A little dirty. No built-in concurrency controls. Results in code that does not (clearly) self-document: is the array in the method signature there so I can pass multiple values? Or is it here as scaffolding for pass-by-reference emulation?

Also see
The answers to StackOverflow question "Mutable boolean field in Java".

My Opinion
In Java, you should strive to use the above approaches sparingly or not at all. In C it is common to use a function's return value to relay a status code (SUCCESS/FAILURE), while a function's actual output is relayed via one or more out-parameters. In Java, it is best to use Exceptions instead of return codes. This frees up method return values to be used for carrying the actual method output -- a design pattern which most Java programmers find to be more natural than out-parameters.

Can I pass a primitive type by reference in Java?

While Java supports overloading, all parameters are passed by value, i.e. assigning a method argument is not visible to the caller.

From your code snippet, you are trying to return a value of different types. Since return types are not part of a method's signature, you can not overload with different return types. Therefore, the usual approach is:

int getIntValue() { ... }
byte getByteValue() { ... }

If this is actually a conversion, the standard naming is

int toInt() { ...}
byte toByte() { ... }

JAVA Pass Primitive type as a Reference to function call

Are you aware of java streams? With streams you can do something like:

List<Object> result = objects.stream()
.filter(object -> {/*add condition here*/})
.map(object->{/*do something with object that match condition above*/})
.collect(Collectors.toList());

You can use this mechanism to collect and process objects based on certain conditions.

If that doesn't help, maybe use an iterator?

Iterator<Object> it = objects.iterator();
while(it.hasNext()){
Object node = someFunction(session,it);
}

public Object someFunction(Session session,Iterator i){
//manipulate i value based on condition
if(true){
i.next();
}else{
i.next();
i.next();
}
}

Passing primitive data by reference in Java

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.

See How do I pass a primitive data type by reference? for more info on mutable wrapper classes.

Passing primitive variables by refence javascript

You can't pass primitives by reference in Javascript - and the example "workaround" does not work. Here's why:

var foo = new Number(2)  // line 1
function inc (arg) { // line 2
arg++ // line 3
}

Line 1 sets foo to a Number object wrapper with primitive value 2.

Line 2 defines a formal parameter arg which has its own storage location in function scope to hold a copy of the value of the argument.

Line 3 increments the actual parameter value (a copy of the Number object reference) where it is stored - in memmory allocated for arg, not foo. If you check the primitive value of foo after the call it is still 2.

In practice you can pass a reference to an object with a foo property that is incremented:

var obj = {}
obj.foo = 2
function incFoo (obj) {
obj.foo++
}
incFoo() // obj.foo now 3

Essentially there are no address pointers available in ECMA script to reference primitive values.

Can I pass primitive types by reference in C#?

Post-update you can pass boxed values around by reference.

static void Main(string[] args)
{
var value = 10;
var boxed = (object)value;
TakesValueByRef(ref boxed);
value = (int)boxed;
// value now contains 5.
}

static void TakesValueByRef(ref object value)
{
value = 5;
}

Just keep in mind it's terrible practice, and risky (due to cast exceptions) to do this.

A reference to primitive type in Java (How to force a primitive data to remain boxed)

Integer is immutable, as you may notice.

Your approach with private static class IntegerWrapper is correct one. Using array with size 1 is also correct, but in practice I have never seen using array for this case. So do use IntegerWrapper.

Exactly the same implementation you can find in Apache org.apache.commons.lang3.mutable.MutableInt.

In your example you also can provide Main instance to the static method:

public class Main {

private int x = 42;

public static void main(String[] args) {
Main main = new Main();
incrementX(main);
}

private static void incrementX(Main main) {
main.x++;
}
}

And finally, from Java8 you could define an inc function and use it to increment value:

public class Main {

private static final IntFunction<Integer> INC = val -> val + 1;

private int x = 42;

public static void main(String[] args) {
Main main = new Main();
main.x = INC.apply(main.x);
}

}

Is there a way to pass a primitive parameter by reference in Dart?

The Dart language does not support this and I doubt it ever will, but the future will tell.

Primitives will be passed by value, and as already mentioned here, the only way to 'pass primitives by reference' is by wrapping them like:

class PrimitiveWrapper {
var value;
PrimitiveWrapper(this.value);
}

void alter(PrimitiveWrapper data) {
data.value++;
}

main() {
var data = new PrimitiveWrapper(5);
print(data.value); // 5
alter(data);
print(data.value); // 6
}

If you don't want to do that, then you need to find another way around your problem.

One case where I see people needing to pass by reference is that they have some sort of value they want to pass to functions in a class:

class Foo {
void doFoo() {
var i = 0;
...
doBar(i); // We want to alter i in doBar().
...
i++;
}

void doBar(i) {
i++;
}
}

In this case you could just make i a class member instead.



Related Topics



Leave a reply



Submit