Pre- and postincrement in Java

后端 未结 6 1700
不思量自难忘°
不思量自难忘° 2021-01-17 13:48

I just wanted to create a little Java-Puzzle, but I puzzled myself. One part of the puzzle is:

What does the following piece of code do:



        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-17 14:36

    You're right regarding the right part evaluation, but you're missing a detail regarding the assignment.

    Run this :

    i = i++;
    

    or this :

    i += i++;
    

    After both operations, i still has its original value.

    That's because i is evaluated on the left before the right part of the assignment.

    So in your case, you're adding 8 to 1, not to 4.

提交回复
热议问题