how can I pass a double value by reference in java?
example:
Double a = 3.0;
Double b = a;
System.out.println(\"a: \"+a+\" b: \"+b);
a = 5.0;
System.
Java doesn't support pointers, so you can't point to a's memory directly (as in C / C++).
Java does support references, but references are only references to Objects. Native (built-in) types cannot be referenced. So when you executed (autoboxing converted the code for you to the following).
Double a = new Double(3.0);
That means that when you execute
Double b = a;
you gain a reference to a's Object. When you opt to change a (autoboxing will eventually convert your code above to this)
a = new Double(5.0);
Which won't impact b's reference to the previously created new Double(3.0)
. In other words, you can't impact b's reference by manipulating a directly (or there's no "action at a distance" in Java).
That said, there are other solutions
public class MutableDouble() {
private double value;
public MutableDouble(double value) {
this.value = value;
}
public double getValue() {
return this.value;
}
public void setValue(double value) {
this.value = value;
}
}
MutableDouble a = new MutableDouble(3.0);
MutableDouble b = a;
a.setValue(5.0);
b.getValue(); // equals 5.0