You changed your parameter, not your class variable. Rename your parameter and it will work:
public static void doChange(Integer unused)
{
x = 2;
}
The reason is that with the assignment (=) you changed the instance. Your parameter x is than assigned to a new instance (not the one you give it with the method call). The solution will be to call instance method to change the state of the instance. But:
the object class of scalar don't work like other classes. The instance of Integer are unique (immutable), you cannot change the state of an Integer instance.
But, if you try it with class of your own like MyNumber and use instance method calls (not assignment =), it will work as you expected:
public class MyNumber {
private int number = 0;
public set(int v) {
number = v;
}
public get() {
return number;
}
public String toString() {
return Integer.toString(number);
}
}
If you use MyNumber instead of Integer change your method doChange to:
public static void doChange(MyNumber x)
{
x.set(2);
}
And of course change the declaration to:
public static MyNumber x;
... and the first assignment in main to:
x.set(1);
Hope it helps to understand.
doChange
, x is the parameter variable, not the global static x.x
todoChange()
. You could simply modifyx
without passing it as a parameter, what is your intention exactly?