Clarification regarding Postfix Increment Operator ++ :java

后端 未结 5 537
情深已故
情深已故 2020-12-17 04:30
int i = 0;
boolean b = true;
System.out.println(b && !(i++ > 0))

When I compile the above code I

5条回答
  •  猫巷女王i
    2020-12-17 05:00

    Java behaving correctly :)

    i++
    

    That is postfix increment.

    It generated result and then incremented that value later.

    !(i++ > 0) // now  value is still zero
    

    i++ will use the previous value of i and then it will increment it.

    When you use ++ ,it's like

    temp=i;
    i += 1; 
    i=temp;     // here old value of i.
    

    language specification on Postfix Increment Operator ++

    the value 1 is added to the value of the variable and the sum is stored back into the variable. ......

    The value of the postfix increment expression is the value of the variable before the new value is stored.

    Possible solution would be ++i, which is as per your requirment,

    Prefix Increment Operator ++

    The value of the prefix increment expression is the value of the variable after the new value is stored.

提交回复
热议问题