Why Java passes objects as references passed by value

This specific content was written 12 years ago. Please keep this in mind as it may be outdated and not adhering to best-practices.

I came across a question recently on stackoverflow that was very enlightening and proves how objects are actually passed in java. It was quite an interesting discovery!

I am quoting from here

 

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



Chris Georgoulis

Summary: - Primary programming language: Java SE (SWING, JDBC), Java EE, (JSF - PrimeFaces, JPA - EclipseLink/Hibernate, EJB, CDI ), - Secondary languages: C/C++, Web Technologies(HTML, XHTML, XML, CSS, JavaScript, jQuery, AngularJS). - Frameworks: Android SDK, Global Sensors Network (GSN), Open Computer Vision (OpenCV). - IDE's: Eclipse, Visual Studio - Other Apps: MS Office, Photoshop, Dreamweaver - Database Design - SQL(MySQL), NoSQL(MongoDB) - Modeling Tools: UML

More Posts