Wednesday, August 6, 2014

Is Java “pass-by-reference” or “pass-by-value”?

Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references and those references are passed by value.
It goes like this:
Dog aDog = new Dog("Max");
foo(aDog);
aDog.getName().equals("Max"); // true

public void foo(Dog d) {
  d.getName().equals("Max"); // true
  d = new Dog("Fifi");
  d.getName().equals("Fifi"); // true
}
In this example aDog.getName() will still return "Max"d is not overwritten in the function as the object reference is passed by value.
Likewise:
Dog aDog = new Dog("Max");
foo(aDog);
aDog.getName().equals("Fifi"); // true

public void foo(Dog d) {
  d.getName().equals("Max"); // true
  d.setName("Fifi");
}

No comments:

Post a Comment