I've been reading this topic: Is Java "pass-by-reference" or "pass-by-value"? , and I've tried to run example from this answer: https://stackoverflow.com/a/73021/2838739 . In fact value of myDog has been changed outside this method. Then I have tried to do the same with an Integer. I was surprised because its value has not been changed. Could someone explain me why?
My test code is:
package testtest;
class Dog {
String name;
public Dog(String name) {
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog("Rover");
System.out.println(myDog.getName());
foo(myDog);
System.out.println(myDog.getName());
Integer i = 5;
changeValue(i);
System.out.println(i);
}
public static void changeValue(Integer i) {
i = 50;
}
public static void foo(Dog someDog) {
someDog.setName("Max"); // AAA
someDog = new Dog("Fifi"); // BBB
someDog.setName("Rowlf"); // CCC
}
}
And output was:
Rover
Max
5
Thank you in advance.