The point is that you want to be able to set the value of i
.
int
s are in Java implemented as primitive data, they are passed-by-value. This means that the following code doesn't set a
:
public void Foo () {
int a = 5;
System.out.println(a);//prints 5
setA(a);
System.out.println(a);//prints 5
}
public void setA (int a) {
a = 3;
}
Java copies the value of the variable on the stack and the copy is modified leaving the original a
untouched.
By using a Wrapper
, you store the int
in an object. Since object
s are passed-by-value from a "variable perspective", or passed-by-reference from the objects perspective, you refer to an object
that contains an int
. In other words, aw
referers to the same instance. Because you copied the reference an not the object. Changes made by the callee are thus reflected in the view of the caller.
public void Foo () {
IntWrapper aw = new IntWrapper();
aw.value = 5;
System.out.println(aw.value);//prints 5
setA(aw);
System.out.println(aw.value);//prints 3
}
public void setA (IntWrapper aw) {
aw.value = 3;
}
This is a useful hack in Java when you want to return multiple values or modify a variable of the caller.
C# alternatively provides the ref
keyword, that enable call-by-reference for primitive values.