I have created an array of primitives and if i executes arr[index]++, then strange enough the content of my array is getting modified. Could someone explain why the content of array is getting modified. I am also pasting the sample code which illustrates the problem :
ExpectedOutput iArr[0] = 0 , tmpArr = [1, 2, 3]
ActualOutput iArr[0] = 1 , tmpArr = [1, 5, 3]
Sample Class:
class ArrayTest {
public static void main(String args[]) {
int i = 1;
int[] iArr = { 0 };
incr(iArr);
System.out.println("iArr[0] = " + iArr[0]);
int[] tmpArr = {1, 2, 3};
for (int j = 0; j < tmpArr.length; j++) {
tmpArr[i]++;
}
System.out.println("tmpArr = " + Arrays.toString(tmpArr));
}
public static void incr(int[] n) {
n[0]++;
}
}
Arrays are effectively collections of variables - so an array access expression refers to a variable, as per section 15.13 of the JLS:
An array access expression refers to a variable that is a component of an array.
...
The result of an array access expression is a variable of type T, namely the variable within the array selected by the value of the index expression.
As it's a variable, it can be incremented as normal - or used in a compound assignment expression, e.g.
x[i] += 10;
In the underlying byte code, this translates into load locally / modify / store instructions.
See more on this question at Stackoverflow