Friday, July 1, 2011

Java is Always Pass-By-Value

This is probably the biggest common misconception in Java. It's starting to become a minor pet-peeve of mine. :P People say things like "Java is pass-by-value for primitives, but pass-by-reference for Objects.". This is not true.

In fact, Java always uses pass-by-value. The trick is that Java always stores references to Objects. When you pass in an object to a method, the object reference is passed by value. This is different than pass-by-reference. Java makes a copy of the reference variable and that's what the method uses. While a lot of the time you won't be able to tell the difference, there are some important cases where this makes a difference.

Here's an example:

The output of this program is:

a: 5
b: 10

This is unexpected behaviour if you think that Java is really pass-by-reference. What this code really did was swap two copies of references, not the references themselves. This caused me a few headaches in the past.

This is a misconception has been around for way too long. Spread the word. :P

1 comment: