Thursday 14 April 2016

Java is pass-by-value!

Java is always pass by value, with no exceptions, ever.

From the JLS1:
When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared type, before execution of the body of the method or constructor.

What this means is that the parameter is actually a copy of the value you provided. Hence, Java is always pass by value.

It is the same for the programming language C3.

It is the same for JavaScript4.

Confusion

The following quote from the JLS2 causes a bit of confusion in the discussion:
An object is a class instance or an array.

The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
So, yes, Java does use pointers (to objects). However, these pointers are passed-by-value! This is why you can change the contents of an object but never switch the object for a different object.

References

[1] JLS SE 8 - 8.4.1. Formal Parameters
http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.1
[2] JLS SE 8 - 4.3.1. Objects
https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.3.1
[3] Dennis Kubes - Is C Pass by Value or Reference?
http://denniskubes.com/2012/08/20/is-c-pass-by-value-or-reference/
[4] What's The Pointy - JavaScript does not have "pass by reference"
http://whatsthepointy.blogspot.nl/2013/11/javascript-does-not-have-pass-by.html
JavaDude.com - Java is Pass-by-Value, Dammit!
http://javadude.com/articles/passbyvalue.htm
StackOverflow - Is Java “pass-by-reference” or “pass-by-value”?
http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value

No comments:

Post a Comment