简体   繁体   English

关于Postfix Increment Operator ++的澄清:java

[英]Clarification regarding Postfix Increment Operator ++ :java

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

When I compile the above code I get a value true back. 当我编译上面的代码时,我得到一个值true。

But how can that be, since the second part of the argument (since b is true already) basically translates to 但是怎么可能呢,因为论证的第二部分(因为b已经是真的)基本上转化为

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

which should return true . 哪个应该返回true Then the statement would be true && false , which is false . 然后声明为true && false ,这是false

What am I missing? 我错过了什么?

Java behaving correctly :) Java表现正确:)

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. i++将使用以前的valuei ,然后它会increment它。

When you use ++ ,it's like 当你使用++时,它就像

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

language specification on Postfix Increment Operator ++ Postfix Increment Operator ++上的语言规范

the value 1 is added to the value of the variable and the sum is stored back into the variable. 将值1添加到变量的值中,并将总和存储回变量中。 ...... ......

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, 可能的解决方案是++i ,根据您的要求,

Prefix Increment Operator ++ 前缀增量运算符++

The value of the prefix increment expression is the value of the variable after the new value is stored. 前缀增量表达式的值是存储新值后变量的值。

You want to use ++i if you want to increment i and return the incremented value. 如果要增加i并返回递增的值,则要使用++i i++ returns the non incremented value. i++返回非递增的值。

b && !(i++ > 0)

i++ is post increment so value of i here is still 0 i++是后增量因此i的值仍为0

0>0 false 0>0

b && 1 is true(since !(0) is 1) b && 1是真的(因为!(0)是1)

So you are getting true. 所以你变得如此。

i++

在执行该行之后会发生增量,因此您最好保留

++i

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 结果是:0 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM