0

1) if(null != parentObj.childObj)

2) if(parentObj.childObj != null)

Do you think that "1" will avoid a potential null pointer exception in the case where 'parentObj' is null, in contrast to "2"?

0

3 Answers 3

5

No.

If parentObj is null then any attempt to call a method or reference a field will result in a NullPointerExcepton. != always evaluates both sides.

Just check if parentObj is null first and handle it appropriately.

Sign up to request clarification or add additional context in comments.

Comments

5

Why not just if(parentObj != null && parentObj.childObj != null) ?

2 Comments

That's what the OP is asking. He's looking to avoid the wordiness of the check.
@Tony Ennis. 1) That's not how I read the question. 2) Anyway, the answer is that he can't, and @irrelephant's answer provides him with the sanest alternative.
1

If parentObj is null, referencing any method/field on parentObj will result in an NPE. In other words, you need if (parentObj != null && parentObj.childObj != null) to avoid an NPE. Groovy cuts down on this (very common) type of verbosity with the safe navigation operator, which lets you write if (parentObj?.childObj).

1 Comment

At one point, the safe navigation operator or something similar might have made it into Java 7 via project Coin. But it didn't make the cut; see blogs.sun.com/darcy/entry/project_coin_final_five

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.