简体   繁体   中英

NullPointerException occuring after null check java

I have this if statement

if((check1==null||!check1.isSolid())&&(check2==null)||!check2.isSolid())

it throws a null pointer exception because check1 or check2 are null, but i don't understand why it is doing this, because i am checking for the null condition before i am accessing the object and if the object is null why would java bother checking isSolid because it would have already been true.

Your messed up your parenthesis. Java will group your statement together like this:

((check1 == null || !check1.isSolid()) && check2 == null) || !check2.isSolid()

If check1 is null and check2 , is null , the first statement will evaluate to true . The problem occurs when your move on to the second statement, since check2 is null , check2.isSolid() will through a NullPointerException .

Change your parenthesis to

(check1 == null || !check1.isSolid()) && (check2 == null || !check2.isSolid())

You mixed up the parentheses. Try:

if((check1==null||!check1.isSolid())&&(check2==null||!check2.isSolid()))

Try this:

boolean check1_result = (check1 == null) ? true : !check1.isSolid();
boolean check2_result = (check2 == null) ? true : !check2.isSolid();

if (check1_result && check2_result)
// do work...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM