David C. answered 04/16/19
CEO/Lead Programmer/Teacher of Java with 8+ Years Experience
You are exactly correct! The AND (&&) does indeed come first, followed by the OR (||).
To walk you through your statement:
First, cat != null && cat.getColor() == "orange" is evaluated. (Though it should be mentioned that to compare Strings, as well as any object data type, you should use .equals() instead of ==. So it would be cat.getColor().equals("orange") and cat.getColor().equals("grey") instead 😊)
Next, the OR statement is evaluated against the outcome of the previous AND.
This particular boolean statement would not work as intended, however. This is because you are checking if the cat is not null and if it's orange, OR if the cat is grey. There is no way to get out of the if statement if the cat is indeed null before checking if it is grey. This can cause a NullPointerException.
To fix this, you would want to put parentheses around the last two thirds of the statement, so that it first checks if the cat is not null, THEN it checks if it is orange or grey.
In example, it would look like this:
if(cat != null && (cat.getColor().equals("orange" ) || cat.getColor().equals("grey")))
{
//stuff
}
If you added parentheses anywhere, those would be evaluated before the AND and the OR. For Java, as well as most all other languages, the order of operations for a boolean statement is as follows:
- ! NOT
- () Parentheses
- && AND
- || OR
I hope this helps!