Reputation: 41
I recently took an entry test in Java and this question confused me. The full question is:
boolean b1 = true;
boolean b2 = false;
if (b2 != b1 != b2)
System.out.println("true");
else
System.out.println("false");
My first question is what (b2 != b1 != b2) means and the second question, as specified in the title, is how (false != true != false) evaluates to true while (true != false != true) evaluates to false (I tested that on Netbeans).
Upvotes: 2
Views: 1196
Reputation: 131386
You have two boolean comparisons where the first comparison produces a result that is compared to another boolean value (the last one).
And the equality operators are syntactically left-associative (they group left-to-right).
To understand you can rewrite the actual comparison by doing the comparison in two times :
1) false != true != false
== true
as
boolean result = false != true; // ->true
result = true != false; // ->true
result == true;
2) true != false != true
== false
as
boolean result = true != false; // -> true
result = true != true; // -> false
result == false;
Or you can also enclose the fist comparison by parenthesis to ease the reading of the evaluations precedence (left to right) :
1) false != true != false
== true
as
<=> (false != true) != false
<=> true != false
<=> true
2) true != false != true
== false
as
<=> (true != false) != true
<=> true != true
<=> false
Upvotes: 6
Reputation: 2686
See what happens most of the compiler start evaluating the expression from left to right So in this case what is happening first it is evaluating this.
False != True == True //is evaluated first which is true
Then it evaluates with this true we got from the first expression
True != False == True //which is also true
So the completer expression goes like this
False != True != False == True// which is True
Now in the second case the expression is like
True != False != True == False
the outputs for fist expression which is True != False evaluates for True and expression becomes True != True which is false
I hope it makes sense. It’s because the associativity of != is from left to right so it evaluating from left to right.
Upvotes: 0
Reputation: 786
it will evaluate this way :
1-false != true != false
= false!=true
=true
so this false != true
became true
and then equation become like this
true
!= false
which is equal to true
so the result is true
.
Now for second one you can evaluate the same way as
2- true != false != true
true!=false
which is true
now true != true
which is false
so you are getting result as false
Upvotes: 0