Eng.Fouad
Eng.Fouad

Reputation: 117597

!flag has two meanings in java?

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?

Upvotes: 1

Views: 21930

Answers (5)

peterm
peterm

Reputation: 1053

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.

Upvotes: 2

user591593
user591593

Reputation:

in human language:

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

Upvotes: 0

Bohemian
Bohemian

Reputation: 425063

!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); 

Upvotes: 2

dlev
dlev

Reputation: 48596

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

Upvotes: 8

sepp2k
sepp2k

Reputation: 370172

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

Upvotes: 2

Related Questions