Clarification regarding Postfix Increment Operator ++ :java

匿名 (未验证) 提交于 2019-12-03 02:15:02

问题:

int i = 0; boolean b = true; System.out.println(b && !(i++ > 0)) 

When I compile the above code I get a value true back.

But how can that be, since the second part of the argument (since b is true already) basically translates to

(0 + 1 > 0) => (1 > 0)

which should return true. Then the statement would be true && false, which is false.

What am I missing?

回答1:

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.



回答2:

You want to use ++i if you want to increment i and return the incremented value. i++ returns the non incremented value.



回答3:

b && !(i++ > 0) 

i++ is post increment so value of i here is still 0

0>0 false

b && 1 is true(since !(0) is 1)

So you are getting true.



回答4:

i++ 

the increment happens after the line is executed so you better keep

++i 


回答5:

You can see how ++ operator works on following example:

public static void main(String[] argv) {     int zero = 0;     System.out.println(zero++);     zero = 0;     System.out.println(++zero); } 

Result is: 0 1



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!