Java uses pass by value (pass reference by value), not pass by reference

I found THIS great article explaining how Java passes objects as methods input parameters. It doesn’t pass them by reference. It passes the value of the reference which for example is something like: “0x00123” etc.

So when you modify an object which is passed as an input parameter the value of the real object which is declared will stay the same even if you change the object which is an input parameter.

 

public void foo(Dog someDog) {
    someDog.setName("Max");     // AAA
    someDog = new Dog("Fifi");  // BBB
    someDog.setName("Rowlf");   // CCC
}

public void main() {
    Dog myDog = new Dog("Rover");
    foo(myDog);
    System.out.println(myDog.getName()) //Max
}

You may also like...