Froskoy Froskoy - 9 months ago 35
Java Question

Are arrays passed by value or passed by reference in Java?

Possible Duplicate:

Is Java “pass-by-reference”?

Arrays are not a primitive type in Java, but they are not objects either, so are they passed by value or by reference? Does it depend on what the array contains, for example references or a primitive type?

Answer Source

Technically, it is passed by value ... but the value is the reference to the array.

Real passing by reference involves passing the address of a variable so that the variable can be updated. This is NOT what happens when you pass an array in Java.

(This Java documentation page may help you understand this: Pitfall: Thinking of variables as objects.)

Here are some links that explain the difference between "pass-by-reference" and "pass-by-value":

Related SO question:

Historical background:

The phrase "pass-by-reference" was originally "call-by-reference", and it was used to distinguish the argument passing semantics of FORTRAN (call-by-reference) from those of ALGOL-60 (call-by-value and call-by-name).

  • In call-by-value, the argument expression is evaluated to a value, and that value is copied to the called method.

  • In call-by-reference, the argument expression is partially evaluated to an "lvalue" (i.e. the address of a variable or array element) that is passed to the calling method. The calling method can then directly read and update the variable / element.

  • In call-by-name, the actual argument expression is passed to the calling method (!!) which can evaluate it multiple times (!!!). This was complicated to implement, and could be used (abused) to write code that was very difficult to understand. Call-by-name was only ever used in Algol-60 (thankfully!).


Actually, Algol-60's call-by-name is similar to passing lambda expressions as parameters. The wrinkle is that these not-exactly-lambda-expressions (they were referred to as "thunks" at the implementation level) can indirectly modify the state of variables that are in scope in the calling procedure / function. That is what made them so hard to understand. (See the Wikipedia page on Jensen's Device for example.)