I tested several different ways of multiplying array elements with a constant.
I got different results depending on how I go through the array, and I had trouble understanding this (I'm pretty new to Java and still get information on how things are passed or referenced).
Test 1
int[] array = {1, 2, 3, 4}; for (int number : array) { number *= 2; }
The result of unmodified array elements:
{1, 2, 3, 4}
It seems that number is not the actual element of the array, but a new int that is initialized with its value. It is right?
Test 2
I thought that using an array of objects could work, assuming that number is a reference to the actual element of the array. Here is my test for using Integer instead of int :
Integer[] array = {1, 2, 3, 4}; for (Integer number : array) { number *= 2; }
Again, as a result of which the elements of the array are not modified:
{1, 2, 3, 4}
Test 3
After some scratching on my head, I tried another loop method, for example:
int[] array = {1, 2, 3, 4}; for (int i = 0; i < array.length; i ++) { array[i] *= 2; }
The result of the multiplication of array elements:
{2, 4, 6, 8}
This end result makes sense to me, but I donβt understand the results of the second test (or, first of all, for this). Until now, I have always believed that the loop used in tests 1 and 2 was just a shorthand for the loop used in test 3, but they are clearly different.
Why does this not work as I expected? Why are these loops different?