Passing by reference in Java?

In C ++, if you need to change 2 objects, you can follow the link. How do you do this in java? Suppose 2 objects are primitive types such as int.

+5
source share
4 answers

You can not. Java does not support passing variable references. Everything is passed by value.

Of course, when a reference to an object is passed by value, it points to the same object, but this does not call the link .

+12
source

Wrap them in an object, and then pass that object as a parameter to the method.

For example, the following C ++ code:

bool divmod(double a, double b, double & dividend, double & remainder) {
  if(b == 0) return false;
  dividend = a / b;
  remainder = a % b;
  return true;
}

can be rewritten in Java as:

class DivRem {
  double dividend;
  double remainder;
}

boolean divmod(double a, double b, DivRem c) {
  if(b == 0) return false;
  c.dividend = a / b;
  c.remainder = a % b;
  return true;
}

Java :

class DivRem {
  double dividend;
  double remainder;
}

DivRem divmod(double a, double b) {
  if(b == 0) throw new ArithmeticException("Divide by zero");
  DivRem c = new DivRem();
  c.dividend = a / b;
  c.remainder = a % b;
  return c;
}
+2

Using generics, you can create a pointer class that will make this at least somewhat less painful. You pass an object, change its value, and when the function exits your object, it will contain a new value.

MyPointerClass<int> PointerClass = new MyPointerClass<int>(5);
myFunction(PointerClass);
System.out.println(PointerClass.Value.toString());

// ...

void myFunction(myPointerClass<int> SomeValue)
{
  SomeValue.Value = 10;
}
0
source

All Articles