To explain what is happening, understanding Java's parameter passing is important; especially whether it's “pass-by-reference” or “pass-by-value”.
Starting off by defining the terms "pass-by-value" semantics and "pass-by-reference" is prudent:
- Pass-by-value: The actual parameter (or argument expression) is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter's value during method/function execution. That location is typically a chunk of memory on the runtime stack for the application (which is how Java handles it), but other languages could choose parameter storage differently.
- Pass-by-reference: The formal parameter merely acts as an alias for the actual parameter. Anytime the method/function uses the formal parameter (for reading or writing), it is actually using the actual parameter.
Java is strictly pass-by-value, exactly like in C. See the following citations from the Java Language Specification (JLS):
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. The Identifier that appears in the
FormalParameter may be used as a simple name in the body of the method
or constructor to refer to the formal parameter.
https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.4.1
The argument expressions (possibly rewritten as described above) are
now evaluated to yield argument values. Each argument value
corresponds to exactly one of the method's n formal parameters.
https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.4.2
Like all Java objects, arrays are passed by value. However, the value is the reference to the array. So, when you assign something to a cell of the array in the called method, you will be assigning to the same array object that the caller sees.
In the code snippet you shared:
public static void main(String[] args)
{
int[] values = {5,2,1,3,8};
mystery(values); // this call will pass the reference by value
for(int v : values)
System.out.println(v + " ");
}
mystery(values)
will pass a reference to the array values
by value and the operations of the receiver mystery(int[] data)
will modify the array values
that is pointed to by that reference.
void
is a return type which implies, as Java is a typed language, the type of the result expected from mystery(int[] data)
.
You can read some more about it here