In Java, what are the boolean "order of operations"?
Solution 1:
The Java Tutorials has a list illustrating operator precedence. The equality operators will be evaluated first, then &&
, then ||
. Parentheses will be evaluated before anything else, so adding them can change the order. This is usually pretty much the same from language to language, but it's always a good idea to double check.
It's the small variations in behavior that you're not expecting that can cause you to spend an entire day debugging, so it's a good idea to put the parentheses in place so you're sure what the order of evaluation will be.
Solution 2:
Boolean order of operations (in all languages I believe):
- parens
- NOT
- AND
- OR
So your logic above is equivalent to:
(cat != null && cat.getColor() == "orange") || cat.getColor() == "grey"