Reputation: 2044
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.
Upvotes: 5
Views: 120
Reputation: 802
If parentheses are not provided then it will be always evaluated from left to right of the equals expression.
Upvotes: 0
Reputation: 1840
According to here, it's:
((( mObject != null ) && a ) || b )
so you should be looking into b, because:
(null != null) is false
false && a is always false
everything depends on b then.
Upvotes: 2
Reputation: 394146
!=
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) )
Upvotes: 4
Reputation: 72884
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.
Upvotes: 7