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.


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.


[1] JLS SE 8 - 8.4.1. Formal Parameters
[2] JLS SE 8 - 4.3.1. Objects
[3] Dennis Kubes - Is C Pass by Value or Reference?
[4] What's The Pointy - JavaScript does not have "pass by reference" - Java is Pass-by-Value, Dammit!
StackOverflow - Is Java “pass-by-reference” or “pass-by-value”?

No comments:

Post a Comment