Question

boolean A = true;
boolean B = false;
boolean C = true;


if(A == true && B == true || C == true);

Is there any reason that I can take for granted that this will evaluate to false? (or true?)

I understand that the best thing here is to wrap the two params that matter in their own parens, but I'm curious about the Java VM and if it's consistent (especially in the case of Delvik). Does it see that B is false and quit (because of the && which seems to require it to be true, if reading it from left to right) or does it natively group the two items on the sides of the || and keep looking to see if C is true (in which case the entire statement ends up being true).

Was it helpful?

Solution

It's not about the VM, the VM works on a lower level and doesn't even see expressions in the same order as you write them in Java. What is important here is operator precedence:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Just like they teach you "multiplication before addition" at school, there's a precedence for all the other operators as well. In Java's case, && has higher precedence than ||. Therefore

(A == true && B == true || C == true)

is equivalent to

((A == true && B == true) || C == true)

But in reality, just like you said, use those parenthesis. It makes it easier to read.

Free protip: == true is superfluous. It doesn't do anything. Replace A == true with just A.

OTHER TIPS

The order is well defined on the Java language level (so it will work on both JVM and Dalvik).

Basically

  • left to right
  • shortcut operators cut short
  • there is operator precendence between && and ||

The latter point I personally can never remember or at least reliably parse quickly, so I always use parens to be explicit. Makes it easier to read.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top