The code is demonstrating the difference between (effectively) call-by-reference (in the first increase method) and call-by-value (in the second increase method). In fact, both methods use call-by-value, but in the first case the value is a reference to an object (the array) and in the second case is an int
(a single value from the array).
The code int[] x = {1, 2, 3, 4, 5}
creates an array. When you call increase(x) you are calling the first increase method. That method iterates through the elements of the array and increments each one. The line x[i]++
is equivalent to x[i] = x[i] + 1
. The results are stored back to the array. By the end of this call, the array now contains {2, 3, 4, 5, 6}
. Hence x[0]
is 2
.
In the second call to increase(int y)
we do not pass in the array, but the value of y[0]
(i.e. 1
). The method increments the variable y
but that has no effect outside of the method. In Java, when you pass a variable it is passed by value which essentially means a copy of the value is passed in. Any changes that are made to that value do not affect the original.
When you pass in the array, you pass a reference to the array object. The reference cannot be changed, but the contents of the object (the contents of the array) can be changed.
I have to admit it is a bit confusing, but re-read what I've written a few times and hopefully you'll get it!