-1

When I run this Java code:

int[] a = new int[10];
    int i = 0,j = 0;
    while(i < 10){
        a[i++] = j+++j++;
    }
    System.out.println(Arrays.toString(a));

I get as output: [1, 5, 9, 13, 17, 21, 25, 29, 33, 37]. Can someone please explain how the statement a[i++] = j+++j++ is resolved.

Gsquare
  • 689
  • 1
  • 5
  • 18
  • It binds like `a[i++] = (j++) + (j++);`. – Sotirios Delimanolis Jul 18 '15 at 06:01
  • It is resolved by whacking the programmer around the head with a programmer management tool (aka a big stick :-) ). Seriously, if you don't write horrible code like that, then you don't need to know what it means. And if someone else writes it .... get out the aforementioned project management tool. – Stephen C Jul 18 '15 at 06:30
  • This is *not* an operator precedence issue. It is an issue of when the side-effects are evaluated. – user207421 Jul 18 '15 at 07:12

2 Answers2

0

The first j++ in the expression j+++j++ increments j and returns its previous value.

The second j++ increments j and returns its previous value, which is the value after the first j++ incremented it.

At the start of next iteration, j is larger by two compared to its value at the start of the previous iteration (since the previous iteration incremented j twice).

Therefore :

a[0] = 0++ + 1++ = 0 + 1 = 1;
a[1] = 2++ + 3++ = 2 + 3 = 5;
a[2] = 4++ + 5++ = 4 + 5 = 9;
...
Eran
  • 374,785
  • 51
  • 663
  • 734
-1

Will be a[i++] = j++ + j++;
i++ translates to use i then increment i

a[0 (i = 1)] = 0 (j = 1) + 1 (j = 2) = 1;
a[1 (i = 2)] = 2 (j = 3) + 3 (j = 4) = 5;
..
Jorj
  • 1,239
  • 1
  • 11
  • 30