Many beginners think that Java is pass-by-reference. The Java specification document says that everything in Java is pass-by-value. There is no such thing as “pass-by-reference” in Java and this is fact. In Java when we pass an object to some method parameter it actually passes objects reference value which many people think that it is passed by reference. To understand this check following example:
public class PassByValueVsRefExample { static 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 static void main(String[] args) { Dog aDog = new Dog("Max"); Dog oldDog = aDog; // we pass the object to some method some(aDog); // aDog variable is still pointing to the "Max" dog when some(...) returns System.out.println(aDog.getName().equals("Max")); // true System.out.println(aDog.getName().equals("Fifi")); // false System.out.println(aDog == oldDog); // true } public static void some(Dog d) { //Here in parameter we are getting value of adog //in reference d of Dog class d.getName().equals("Max"); // true // change value of d (ref to Dog) to new object d = new Dog("Fifi"); System.out.println(d.getName().equals("Fifi")); // true } }
In the above example, we are creating an object aDog, and assigning it’s reference to another reference variable oldDog.
After this, we are passing aDog object to method some. In some method, we are getting the value of aDog reference in d. Again inside method some we are assigning the new object to reference d. After method call value of aDog object and oldDog object is unchanged.