Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check for null values in Java?

Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException.

What is the best way to go about this? I've considered these methods.
Which one is the best programming practice for Java?

// Method 1 if (foo != null) {     if (foo.bar()) {         etc...     } }  // Method 2 if (foo != null ? foo.bar() : false) {     etc... }  // Method 3 try {     if (foo.bar()) {         etc...     } } catch (NullPointerException e) { }  // Method 4 -- Would this work, or would it still call foo.bar()? if (foo != null && foo.bar()) {     etc... } 
like image 933
JamieGL Avatar asked Jun 25 '13 16:06

JamieGL


People also ask

Can you use == for null in Java?

== and !=The comparison and not equal to operators are allowed with null in Java. This can made useful in checking of null with objects in java.

IS null == null in Java?

out. println("(Object)string == number: " + ((Object)string == number)); To conclude this post and answer the titular question Does null equal null in Java? the answer is a simple yes.

Should I always check for null Java?

In any case, it is always good practice to CHECK for nulls on ANY parameters passed in before you attempt to operate on them, so you don't get NullPointerExceptions when someone passes you bad data. Show activity on this post. If you don't know whether you should do it, the chances are, you don't need to do it.


2 Answers

Method 4 is best.

if(foo != null && foo.bar()) {    someStuff(); } 

will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.

like image 184
Jared Nielsen Avatar answered Oct 06 '22 02:10

Jared Nielsen


The last and the best one. i.e LOGICAL AND

  if (foo != null && foo.bar()) {     etc... } 

Because in logical &&

it is not necessary to know what the right hand side is, the result must be false

Prefer to read :Java logical operator short-circuiting

like image 32
Suresh Atta Avatar answered Oct 06 '22 02:10

Suresh Atta