Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logic evaluation with && and || in a statement

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.

like image 237
Simon Meyer Avatar asked Dec 11 '22 01:12

Simon Meyer


2 Answers

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.

like image 148
M A Avatar answered Dec 28 '22 06:12

M A


!= 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) )
like image 21
Eran Avatar answered Dec 28 '22 06:12

Eran