unable to make out this assignment in java

前端 未结 4 2097
长发绾君心
长发绾君心 2020-12-06 18:32

can anybody explain this why its happening

int i=0;
i=i++;
i=i++;
i=i++;
System.out.println(i);

it prints zero.

4条回答
  •  [愿得一人]
    2020-12-06 19:13

    i++ is a postincrement (JLS 15.14.2). It increments i, but the result of the expression is the value of i before the increment. Assigning this value back to i in effect keeps the value of i unchanged.

    Break it down like this:

    int i = 0;
    int j = i++;
    

    It's easy to see why j == 0 in this case. Now, instead of j, we substitute the left hand side with i. The right hand side value is still 0, and that's why you get i == 0 in your snippet.

提交回复
热议问题