a += a++ * a++ * a++ in Java. How does it get evaluated?

前端 未结 6 609
旧时难觅i
旧时难觅i 2020-12-10 15:27

I came across this problem in this website, and tried it in Eclipse but couldn\'t understand how exactly they are evaluated.

    int x = 3, y = 7, z = 4;

          


        
6条回答
  •  情书的邮戳
    2020-12-10 15:45

    Because the increment Operation ++ is added after the variable x. That's a post increment operation. That means, x is incremented after the operation is handled.

    In your example the expression would be: 
    x += 3 * 4 * 5
    First the expression is added by 3 (x+=....)
    then the first x++ results in 3
    the second x++ results in 4 (because it was incremented before)
    and the third x++ results in 5.
    

    If you want your variable incremented before the operation is executed, you have to write ++x (pre increment operation)

提交回复
热议问题