I'm just debugging some code and found some expression:
if (mObject != null && a || b )
{
mObject.someMethod();
}
which had a NullPointerException in the mObject.someMethod() line - so my question is:
how is the expression evaluated?
1. a && b || c == a && (b || c)
or
2. a && b || c == (a && b) || c
If 1. is the case i'd probably have to look at some multithreading issues.
This is probably a dumb question and i'm pretty sure it has been asked before, but i can't find the answer here. Thanks for the answers in advance.
It is equivalent to the following condition:
if ((mObject != null && a) || b )
&&
has a higher precedence that ||
.
If mObject
is null, the condition may pass if b
is true.
!=
has precedence over &&
which has precedence over ||
(Source)
Therefore
if (mObject != null && a || b )
is equivalent to
if (((mObject != null) && a) || b )
To avoid the exception, use parentheses :
if (mObject != null && (a || b) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With