Reputation: 1349
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)?
Upvotes: 1
Views: 154
Reputation: 5947
It is called Pass by value. When you pass some object to dome method, Java creates a copy of reference to that object. If you check object's hashcode right after going into method's body it will be the same as passed object's one. But when you change it inside of method, object changes and reference is no longer points to same object.
EDIT: code sample
public class TestPass {
public static void main(String[] args) {
String ss= "sample";
System.out.println("Outside method: "+ss.hashCode());
method(ss);
}
static void method(String s){
System.out.println("Inside method: "+s.hashCode());
s+='!';
System.out.println("Inside method after object change: "+s.hashCode());
}
}
Output:
Outside method: -909675094
Inside method: -909675094
Inside method after change: 1864843191
Upvotes: 1
Reputation: 4693
objects as parameters in Java are transferred as a params by copy of reference - so if you change the object via reference copy - you will have your object updated.
in case of your upd(Integer val)
method you create a new Integer
object so that reference copy now point to a new object, not the old one. So changing that object will not affect the original one.
Upvotes: 1
Reputation: 39632
Because for Integer
your are creating a new Object. For Man
you just change one of its value, the object man
stays the same.
Consider the following:
static void updMan(Man man) {
man = new Man();
man.name = "Another Man";
}
This would also not change your initial man
.
--EDIT
You can "simulate" the mutability of Integer
by this:
static void upd(Integer val) {
try {
Field declaredField = val.getClass().getDeclaredField("value");
declaredField.setAccessible(true);
declaredField.set(val, 42);
} catch (Exception e) {
}
}
Upvotes: 1
Reputation: 8614
man.name = "Name";
You are actually changing something in the same object here and not creating a new object as you did in In case of Integer.
Upvotes: 0