!flag has two meanings in java?

2019-08-01 09:02发布

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?

5条回答
Bombasti
2楼-- · 2019-08-01 09:40

!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); 
查看更多
戒情不戒烟
3楼-- · 2019-08-01 09:42

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

查看更多
疯言疯语
4楼-- · 2019-08-01 09:44

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

查看更多
祖国的老花朵
5楼-- · 2019-08-01 09:44

in human language:

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

查看更多
我只想做你的唯一
6楼-- · 2019-08-01 09:51

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.

查看更多
登录 后发表回答