0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.