-1
    int i = 1;
    i = i++;
    int j = i++;
    int k = i + ++i * i++;
    System.out.println("i==" + i);
    System.out.println("j==" + j);
    System.out.println("k==" + k);

Why the result of k is 11? I'm a learner of java. Please help me and explain what's going on under the hood or give me some pointers about where I can find related learning resources if possible.

Liu
  • 67
  • 1
  • 6
  • Try stepping through the code with a debugger – rdas Mar 29 '20 at 09:42
  • @TongChen can you explain why? – Jens Mar 29 '20 at 09:50
  • 1
    Does this answer your question? [How do the post increment (i++) and pre increment (++i) operators work in Java?](https://stackoverflow.com/questions/2371118/how-do-the-post-increment-i-and-pre-increment-i-operators-work-in-java) – dawis11 Mar 29 '20 at 09:51

1 Answers1

0
int i = 1; // i == 1
i = i++; // i is incremented, but the original value of i is assigned back to i, so i == 1
int j = i++; // i == 2
int k = i + ++i * i++; // k = 2 (the original value of i before this statement) + 
                       //     3 (the result of pre-incrementing i) * 
                       //     3 (the result of post-incrementing i is still 3) == 11
System.out.println("i==" + i);
System.out.println("j==" + j);
System.out.println("k==" + k);

Note that 2 + 3 * 3 is evaluated as 2 + (3 * 3).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • since ++i changes the value of i, why does k equal 2 + 3 * 3, not 4+ 3 * 3? – Liu Mar 29 '20 at 10:08
  • 1
    @AndyLiu the operands of the `+` operator are evaluated left to right. First `i` is evaluated, then `++i * i++` is evaluated, and finally the two are added. When `i` is evaluated, it is still equal to 2. – Eran Mar 29 '20 at 10:15