Search code examples
javalanguage-lawyeroperator-precedence

Why highest priority operation [ ] is not evaluated first ini = i + arr[i++] + arr[i++]?


[ ] priority is highest (anyway is higher than +). But in RHS of expression below the first (leftmost) summand (i) is evaluated before the second summand arr1[i++], because i++ of arr1[i++] does not influence value of the first (leftmost) summand (i which is 1 and not changed).

I cannot strictly explain why higher priority [ ] is not evaluated first.

int[] arr = { 0, 0, 0 };
int i = 1;
i = i + arr[i++] + arr[i++];
System.out.println(i); // output is zero

Solution

  • See jls Evaluate Operands before Operation:

    The Java programming language guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.

    and Evaluate Left-Hand Operand First

    The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.

    The most left operand is evaluated as 1 before i++.