I’ve got a question.
public class Jaba {
public static void main(String args[]) {
Integer i = new Integer(0);
new A(i);
System.out.println(i);
new B(i);
System.out.println(i);
int ii = 0;
new A(ii);
System.out.println(ii);
new B(ii);
System.out.println(ii);
}
}
class A {
public A(Integer i) { ++i; }
}
class B {
public B(int i) { ++i; }
}
To my mind passing an int\Integer as Integer to a function and making ++ on that reference should change the underlying object, but the output is 0 in all the cases. Why is that?
As said in the other answers, Java does only call-by-value, and the
++operator only effects a variable, not an object. If you want to simulate call-by-reference, you would need to pass a mutable object, like an array, and modify its elements.The Java API has some specialized objects for this, like
java.util.concurrent.atomic.AtomicInteger(which additionally also works over multiple threads), andorg.omg.CORBA.IntHolder(used for call-by-reference for remote calls by the CORBA mechanism).But you can also simply define your own mutable integer: