Reputation: 23
Can anybody explain the logic behind the output of below code?
if(true||false&&false){
System.out.println("right to left ");
}
if (false && true||true){
System.out.println("left to right");
}
Upvotes: 2
Views: 95
Reputation: 4223
First of all such if cases are eliminated at compile time, as long as the result is constant.
||(or) - addition
&&(and) - multiplication
that's why && has a higher precedence than ||
So by precedence expressions are equal to:
true + (false * false)
and (false * true) + true
Upvotes: 0
Reputation: 67320
if(true||false&&false)
can be simplified to true so it prints the line. It can be simplified to true because you have a true
on the left hand side. Since there's an or/||
on the right of it, and things are already true, it means it can short circuit and not evaluate the rest. You can prove this to yourself by taking the false&&false
, putting it in its own method, and then printing a line before it returns. You'll see that it doesn't print. That's because the (false && false)
is not even evaluated.
false && true||true
can be simplified to true so it prints the line. The false && true
evaluates to false, but since there's an or left over, it evaluates the other side of that. That turns out to be true. Since false||true
== true
, that evaluates to true. There is no short circuiting here though. You can prove this by extracting the false && true
into its own method and printing something on the first line. You'll see that it prints:
public static void main(String args[]) {
if(true|| doSomething()){
System.out.println("right to left ");
}
if (doSomethingElse() ||true){
System.out.println("left to right");
}
}
private static boolean doSomething() {
System.out.println("do something"); //this does NOT print
return false&&false;
}
private static boolean doSomethingElse() {
System.out.println("do something else"); //this DOES print
return false && true;
}
Upvotes: 1
Reputation: 46209
If you take a look at this Operator precedence table, you can see that &&
has a higher precedence than ||
.
Therefore, the two expressions are evaluated like this:
true || false && false
== true || (false && false)
== true
false && true || true
== (false && true) || true
== true
Upvotes: 5
Reputation: 5208
Java gives the different operator precedence to &&
and ||
. That means your expressions can be written as true || (false && false)
and (false && true) || true
. When you see an "or true" in a boolean expression, it's always true. Which is why both strings are printed.
If you want your expressions to be clear, you can always put brackets around the x && y
parts.
Upvotes: 1