Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass by reference/value - simple example

Tags:

java

I know this issue has been addressed many times - but my Java/C++ knowledge is so weak I can barely understand the answers :-( ... what I'd really like is just a super simple example.

In C++ I could write the following:

void func()
{
  int x = 3;
  add_one(x);
  // now x is 4.
}
void add_one(int &var)
{
  var++;
}

What I'd like to see now is the simplest way to achieve the same effect with java.

like image 708
Mick Avatar asked Jul 11 '12 16:07

Mick


3 Answers

You can't directly. The closest you can get is to put the value in an object, and pass the reference (by value, so the reference gets copied) into the method.

void func()
{
  int x = 3;
  int[] holder = [x];
  add_one(holder);
  // now holder[0] is 4.  x is still 3.
}

// container here is a copy of the reference holder in the calling scope.
// both container and holder point to the same underlying array object
void add_one(int[] container)
{
    container[0]++;
}

Here I use an array, but the wrapper can be any object.

like image 89
hvgotcodes Avatar answered Oct 20 '22 05:10

hvgotcodes


In java method arguments are pass-by-value, and can't be changed in the function. You must wrap the int - or any other primitive type - in an Object or an array. Passing an Object or an array as a method argument passes a reference which can be used to modify the object.

Java already has Object based wrappers for primitive types, e.g. Integer, but these are immutable by design. Some libraries provide mutable versions of these wrappers; you can also create your own:

public class MutableInt
{
    private int val;

    public MutableInt(int val)
    {
        this.val = val;
    }

    public void setValue(int newVal)
    {
        this.val = newVal;
    }

    public int getValue()
    {
        return this.val;
    }
}

void func()
{
    int x = 3;
    MutableInt wrapper = new MutableInt(x);
    add_one(wrapper);
}

void add_one(MutableInt arg)
{
    arg.setValue(arg.getValue() + 1);
}
like image 37
pb2q Avatar answered Oct 20 '22 04:10

pb2q


You cannot do this. Java is only pass by value. Primitives are obvious, but the thing that's passed for objects is a reference, not the object itself.

like image 25
duffymo Avatar answered Oct 20 '22 05:10

duffymo