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?
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?
!flag
does not change the value offlag
, it merely negates it when evaluating it.Since
flag = false
,!flag
is identical to!false
which istrue
.Your code is equivalent to this:
which is equivalent to:
!flag
whereflag
isfalse
evaluates totrue
in all contexts, including if statements.It's not.
if (boolean expression) { statement }
means "execute thestatement
ifboolean expression
is true." Sinceflag = false
,!flag == true
. Always.in human language:
if flag is not true, print out the opposite value of "flag"
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 astrue
.Now,
flag
is equal tofalse
. This means that negation offlag
will betrue
(!false = true
). This is why tne statement inside the if confition is performed and writestrue
(the negated value offlag
) to your console output.