-1

[ ] 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
inqi777
  • 89
  • 2
  • 5

2 Answers2

0

This behaves how I'd expect it to, frankly. The operator precedence seems correct.

Given this sample code, we would expect the result to not be negative.

int[] arr = {-1000, 100, 150};
int i = 1;
i = i + arr[i++] + arr[i--];
System.out.println(i);

Here's what happens.

  • + associates right-to-left, but it has a lower priority than [], so it is not invoked yet.
  • arr[i++] resolves first, and results in 100, with i == 2.
  • arr[i--] resolves next, and results in 150, with i == 1.
  • + resolves next, left to right, and adds 150 + 100 + 1.
  • The answer then becomes 251.

So, to answer your question...yes, the array access is happening first.

Makoto
  • 104,088
  • 27
  • 192
  • 230
0

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++.

xingbin
  • 27,410
  • 9
  • 53
  • 103