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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:49:51  来源:igfitidea点击:

!flag has two meanings in java?

javaif-statementnot-operator

提问by Eng.Fouad

boolean flag = false;
if(!flag) System.out.println(!flag); // prints true

I wonder why !flagbeing considered as falsewhen it's a conditional parameter passed to if statementand as trueelsewhere?

我不知道为什么!flag被认为是false当它是一个有条件的参数传递到if statementtrue其他地方?

回答by dlev

It's not. if (boolean expression) { statement }means "execute the statementif boolean expressionis true." Since flag = false, !flag == true. Always.

不是。if (boolean expression) { statement }意思是“执行statementifboolean expression为真”。由于flag = false, !flag == true. 总是。

回答by mouser

Well, you are probably misinterpreting the evaluation of conditional operator. The ifoperator performs the statements inside, if and only if the condition is evaluated as true.

好吧,您可能误解了条件运算符的评估。的if操作者执行的语句中,当且仅当该条件为评价true

Now, flagis equal to false. This means that negation of flagwill 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。这意味着flagwill 的否定是true( !false = true)。这就是为什么执行 if confition 中的 tne 语句并将true( 的否定值flag)写入控制台输出的原因。

回答by Bohemian

!flagdoes not changethe value of flag, it merely negates it when evaluatingit.

!flag不会改变的值flag,它只是在评估它时否定它。

Since flag = false, !flagis identical to !falsewhich 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

!flagwhere flagis falseevaluates to truein all contexts, including if statements.

!flagwhere flagis在所有上下文中false计算为true,包括 if 语句。

回答by Eng.Fouad

in human language:

用人类语言:

if flag is not true, print out the opposite value of "flag"

如果 flag 不为真,则打印出“flag”的相反值