!flag has two meanings in java?

試著忘記壹切 提交于 2019-12-24 08:05:28

问题


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?


回答1:


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




回答2:


!flag where flag is false evaluates to true in all contexts, including if statements.




回答3:


!flag does not change the value of flag, it merely negates it when evaluating it.

Since flag = false, !flag is identical to !false which is true.
Your code is equivalent to this:

if (!false) System.out.println(!false); 

which is equivalent to:

if (true) System.out.println(true); 



回答4:


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.

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.




回答5:


in human language:

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



来源:https://stackoverflow.com/questions/6658511/flag-has-two-meanings-in-java

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