简体   繁体   中英

Evaluating an expression with multiple boolean values

This might seem quite straight forward to most of the programmers, but I was a little surprised to see the following code print true .

//The actual implementation has proper logic, 
//just for simplicity I am using booleans in place of those logics

System.out.println(false && false || true && true || false && false);

Because my perception was that - if the 1st boolean value evaluates to false and the next operand is && then the jvm will not even try to evaluate the rest of the expression and just consider the whole as false

I was expecting code like below to work, but not the above one:

System.out.println((false && false) || (true && true) || (false && false));

Is it like the compiler by default groups the && s between || s

Is it like the compiler by default groups the &&s between ||s

That's exactly what it does. It's called operator precedence . Languages explicitly define it because otherwise operations could be ambiguous, and ambiguity can't be allowed by a compiler.

A simpler example of operator precendence would be something like:

x = 1 + 2 * 3;

Would you expect the result to be 9 or 7? Operator precedence defines unambiguously what the result must be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM