Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are arrays in java pass by reference or pass by value?

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

Suppose I have an array called data that contains objects of some type. Now let us suppose that I pass and store that array in class A and then I pass it to class B and class B changes one of the entries of the array. Will class A's version of the array change? Does it matter if this was an array of primitives (such as int) instead? What about ArrayLists?

like image 697
Nosrettap Avatar asked Sep 03 '25 02:09

Nosrettap


1 Answers

Everything in Java is pass-by-value. However, if you're passing a reference, it's the value of the reference.

Since Java methods can't reach into the caller's stack to reassign variables, no method call can change the identity of a reference (address) there. This is what we mean when we say Java is not pass-by-reference. This contrasts with C++ (and similar languages), which allows this in some cases.

Now let's look at some effects.

If I do:

Object[] o = ...
mutateArray(o);

the contents can be different afterwards, since all mutateArray needs is the address of an array to change its contents. However, the address of o will be the same. If I do:

String x = "foo";
tryToMutateString(x);

the address of x is again the same afterwards. Since strings are immutable, this implies that it will also still be "foo".

To mutate an object is to change the contents of it (e.g. successfully changing the last element of o, or trying to change the last letter of "foo" to 'd'). This should not be be confused with reassigning x or o in the caller's stack (impossible).

The Wikipedia section on call by sharing may shed additional light.

like image 141
Matthew Flaschen Avatar answered Sep 07 '25 14:09

Matthew Flaschen