-1

I am checking to see if an object is null before using it like this

if (resturant.getLat() != null)
   //do stuff

But it is throwing a java.lang.NullPointerException how can I check that restaurant.getLat() is not null?

Thanks

spen123
  • 3,464
  • 11
  • 39
  • 52

1 Answers1

5

You need to write if (restaurant != null && restaurant.getLat() != null)

This is because restaurant itself might be null.

If statements in Java are evaluated from left to right && is short-circutted; meaning that once the value of the expression is known, evaluation stops. So the way I've written it is idiomatic.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    *"If statements in Java are evaluated from left to right and are short-circutted"* Not true. You can write `if` that doesn't short-circuit: `if (restaurant != null & restaurant.getLat() != null)`. It's the operators `&&` and `||` that short-circuit, not `if`. – m0skit0 Aug 12 '15 at 14:53
  • @m0skit0: Good point, I should be more careful. We'll publish jointly. Have amended. – Bathsheba Aug 12 '15 at 14:54