I am confused with one trivial thing – passing parameters to the method and changing their values… I’ll better give you some code:
public class Test {
public static void main(String[] args) {
Integer val = new Integer(41);
upd(val);
System.out.println(val);
Man man = new Man();
updMan(man);
System.out.println(man.name);
}
static void upd(Integer val) {
val = new Integer(42);
}
static void updMan(Man man) {
man.name = "Name";
}
static class Man {
String name;
}
}
Could you explain why the Integer object I’ve passed is not updated while the Man object is? Aren’t the Integer and Man objects passed by reference (due to their non-primitive nature)?
Because for
Integeryour are creating a new Object. ForManyou just change one of its value, the objectmanstays the same.Consider the following:
This would also not change your initial
man.–EDIT
You can “simulate” the mutability of
Integerby this: