Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the value by reference in java

public class JavaApplication6 {

    public static void a(int b)
    {
        b++;
    }

I am calling the function a and passing the variable b with the intention of incrementing it like a C++ reference (&b). Will this work? If not, why?

    public static void main(String[] args) {

        int b=0;
        a(b);
        System.out.println(b);
    }

}
like image 473
striker Avatar asked Oct 10 '16 17:10

striker


2 Answers

While you can't really accomplish that with int (the primitive type for integer), you can accomplish something very similar with AtomicInteger. Simply invoke the getAndIncrement method on an instance of the class. Something like this:

public static void a(AtomicInteger b) {
    b.getAndIncrement();
}

(Note that you also can't do this with java.lang.Integer, because java.lang.Integer is an immutable class.)

like image 116
nasukkin Avatar answered Oct 07 '22 04:10

nasukkin


First of all: Java does not allow for pass-by-reference. Further, out-parameters (when a function's calculations/results are placed in one or more of the variables passed to it) are not used; instead, something is returned from a method like so:

b = a(b);

Otherwise, in Java, you pass objects as pointers (which are incorrectly called references). Unfortunately (in your case) most types corresponding to int (Integer, BigInteger, etc.) are immutable, so you cannot change the properties in the object without creating a new one. You can, however, make your own implementation:

public static class MutableInteger {
    public int value;

    public MutableInteger(int value) {
        this.value = value;
    }
}

public static void main(String[] args) {
    MutableInteger b = new MutableInteger(2);
    increment(b);
    System.out.println(b.value);
}

public static void increment(MutableInteger mutableInteger) {
    mutableInteger.value++;
}

The following will be printed to the console when this code is run:

3

At the end of the day, using the above requires a strong argument on the programmer's part.

like image 42
Patrick Favre Avatar answered Oct 07 '22 05:10

Patrick Favre