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... }
== 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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With