3

My function takes as input two Double objects, and I would like to modify them both inside the function. It seems it is not possible, it seems java copies them inside the function. How is this done in java, in c++ you pass by reference.

Thanks

user1796942
  • 3,228
  • 5
  • 29
  • 38

6 Answers6

12

Wrapper classes are immutable, that is the reason you were unable to modify them. One way is , you may create one class with these two attributes and pass it to the function, inside function, set new values to that object.

kosa
  • 65,990
  • 13
  • 130
  • 167
3

What you can do is wrap the Double objects into a Wrapper class, and modify the doubles stored in that object. Otherwise, no other way, as the only value you will change is the local argument.

public class DoubleWrapper
{
  private double d1, d2; 
  public void setter(double newdouble){} 
  public double getter() {}
}
Lews Therin
  • 10,907
  • 4
  • 48
  • 72
2

Pass the double values in an array, you can modify array elements in your function.

Waqas Ilyas
  • 3,116
  • 1
  • 17
  • 27
0

Java is call by value, so you're right: It must be done in another manner.

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
0

There are two issues here:

First, all values in Java are pass-by-value. This means that, when an object X is sent to a function, that function holds a new version of X.

Second, you can't modify a Double value. You have to modify a double, and can convert from Double d to double by running d.doubleValue().

0

In general you shouldn't be modifying arguments in Java (or perhaps any language)

Instead I suggest you return the values changed as an array

public static double[] square(double... doubles) {
     double[] ret = new double[doubles.length];
     for(int i = 0; i < doubles.length; i++)
         ret[i] = doubles[i] * doubles[i];
     return ret;
}

Ideally, you would have a class which wraps these doubles and you call a method to alter them

class MyDoubles {
     double d1, d2;

     public void squareDoubles() {
         d1 *= d1;
         d2 *= d2;
     }

     public String toString() { return "{ " + d1 +", " + d2 + "}"; }
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130