Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested array references

Tags:

java

arrays

I'm currently learning Java online and am confused about the following code and what one of the elements in the array is evaluating to:

int[] a = new int[]{9, 8, 3, 1, 5, 4};

for (int i = 0; i < a.length; i++) {
    if (a[i] % 2 == 0) {
        a[i] += 1;
    } else if (a[i] < a.length) {
        a[i] += a[a[i]];
    }
}

I am looking at a[3] and the number that this evaluates to, and when I am debugging the code, my IDE is showing that a[a[i]] is evaluating to 9, which is where I'm a bit confused.

I thought that a[3] would equal 1 and then a[1] would equal 8, however this doesn't seem to be the case. Could anyone provide clarity as the JetBrains Academy course doesn't refer to this.

like image 586
Lorcan Avatar asked Sep 17 '19 12:09

Lorcan


1 Answers

Note the first condition - if (a[i] % 2 == 0) {a[i] += 1;} - this causes even values to be incremented. Therefore a[1] is incremented from 8 to 9.

Now, when i==3, a[a[i]] is evaluated to a[1] which is equal to 9. Then you are adding it to the original value of a[3] (note the operator is +=, not =), so a[3] becomes 1 + 9, which is 10.

like image 150
Eran Avatar answered Sep 19 '22 21:09

Eran