After running the code below I get this output:
Eve
1200
Could anyone explain me why the value of Person type variable is being changed and value of Integer type variable is not?
I have already read this:
- http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
- http://www.yoda.arachsys.com/java/passing.html#formal
but I don’t get why with Person and Integer types it works different.
public class Test {
public static void main(String[] args) {
Object person = new Person("Adam");
Object integer = new Integer("1200");
changePerson(person);
changeInteger(integer);
System.out.println(person);
System.out.println(integer);
}
private static void changeInteger(Object integer) {
integer = 1000;
}
private static void changePerson(Object person) {
((Person)person).name="Eve";
}
}
In Java, primitive types (such as integer) are always handled exclusively by value, and objects (such as your Person) and arrays are always handled exclusively by reference.
If you pass a primitive the value will be copied, if you pass a reference type the address will be copied, hence the differences.
If you follow those links above and/or do a bit of googlin’ you’ll find out more.