0

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.

4
  • 2
    try this : if( (check1==null||!check1.isSolid() ) &&( (check2==null)||!check2.isSolid() ) ) Commented Mar 30, 2013 at 1:11
  • @Satya - It looks like you just added some whitespace. That isn't going to make any difference. Commented Mar 30, 2013 at 1:13
  • 2
    Stephen I corrected the parenthesis as well Commented Mar 30, 2013 at 1:14
  • 1
    For the future, you can do yourself a favor and not try to jam all that together with no newlines and spacing =) Commented Mar 30, 2013 at 1:20

3 Answers 3

5

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())
Sign up to request clarification or add additional context in comments.

Comments

1

You mixed up the parentheses. Try:

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

Comments

1

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...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.