!flag has two meanings in java?

2019-08-01 09:45发布

问题:

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"