Tuesday 18 June 2013

Is Java “pass-by-reference”?

Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references passed by value.

It goes like this:

public void foo(Dog d) {
  d.name.equals("Max"); // true
  d = new Dog("Fifi");
  d.name.equals("Fifi"); // true
}

Dog aDog = new Dog("Max");
foo(aDog);
aDog.name.equals("Max"); // true

In this example aDog.name will still be "Max". "d" is not overwritten in the function as the object reference is passed by value. Likewise:

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

Dog aDog = new Dog("Max");
foo(aDog);
aDog.name.equals("Fifi"); // true


EmoticonEmoticon