java !flag 在java中有两种含义?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6658511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
!flag has two meanings in java?
提问by Eng.Fouad
boolean flag = false;
if(!flag) System.out.println(!flag); // prints true
I wonder why !flag
being considered as false
when it's a conditional parameter passed to if statement
and as true
elsewhere?
我不知道为什么!flag
被认为是false
当它是一个有条件的参数传递到if statement
和true
其他地方?
回答by dlev
It's not. if (boolean expression) { statement }
means "execute the statement
if boolean expression
is true." Since flag = false
, !flag == true
. Always.
不是。if (boolean expression) { statement }
意思是“执行statement
ifboolean expression
为真”。由于flag = false
, !flag == true
. 总是。
回答by mouser
Well, you are probably misinterpreting the evaluation of conditional operator. The if
operator performs the statements inside, if and only if the condition is evaluated as true
.
好吧,您可能误解了条件运算符的评估。的if
操作者执行的语句中,当且仅当该条件为评价true
。
Now, flag
is equal to false
. This means that negation of flag
will be true
(!false = true
). This is why tne statement inside the if confition is performed and writes true
(the negated value of flag
) to your console output.
现在,flag
等于false
。这意味着flag
will 的否定是true
( !false = true
)。这就是为什么执行 if confition 中的 tne 语句并将true
( 的否定值flag
)写入控制台输出的原因。
回答by Bohemian
!flag
does not changethe value of flag
, it merely negates it when evaluatingit.
!flag
不会改变的值flag
,它只是在评估它时否定它。
Since flag = false
, !flag
is identical to !false
which is true
.
Your code is equivalent to this:
因为flag = false
,!flag
是相同的!false
,其是true
。
您的代码等效于:
if (!false) System.out.println(!false);
which is equivalent to:
这相当于:
if (true) System.out.println(true);
回答by sepp2k
!flag
where flag
is false
evaluates to true
in all contexts, including if statements.
!flag
where flag
is在所有上下文中false
计算为true
,包括 if 语句。
回答by Eng.Fouad
in human language:
用人类语言:
if flag is not true, print out the opposite value of "flag"
如果 flag 不为真,则打印出“flag”的相反值