Best way to check for null values in Java?

255,576

Solution 1

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.

Solution 2

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

Solution 3

Since java 8 you can use Objects.nonNull(Object obj)

if(nonNull(foo)){ 
//
}

Solution 4

  • Do not catch NullPointerException. That is a bad practice. It is better to ensure that the value is not null.
  • Method #4 will work for you. It will not evaluate the second condition, because Java has short-circuiting (i.e., subsequent conditions will not be evaluated if they do not change the end-result of the boolean expression). In this case, if the first expression of a logical AND evaluates to false, subsequent expressions do not need to be evaluated.

Solution 5

Method 4 is far and away the best as it clearly indicates what will happen and uses the minimum of code.

Method 3 is just wrong on every level. You know the item may be null so it's not an exceptional situation it's something you should check for.

Method 2 is just making it more complicated than it needs to be.

Method 1 is just method 4 with an extra line of code.

Share:
255,576
JamieGL
Author by

JamieGL

Hi there, I'm Jamie Lievesley - aka JamieGL or ArtyFishL ๐Ÿ‘‹ Senior Software Engineer at Biotronics 3D ๐Ÿ‘จโ€๐Ÿ’ป Full-stack developer. ๐ŸŽจ UX design. ๐Ÿฉบ Medical imaging: RIS, PACS, HL7, DICOM. ๐Ÿ“ฑ Creating for the web, desktop and mobile devices. ๐Ÿงช I experiment and make projects for fun. ๐Ÿด๓ ง๓ ข๓ ณ๓ ฃ๓ ด๓ ฟ Scottish. Languages and Tools: Web Native Tools

Updated on July 08, 2022

Comments

  • JamieGL
    JamieGL almost 2 years

    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...
    }
    
  • JamieGL
    JamieGL almost 11 years
    Thanks, I thought that would be best, but I wasn't sure why it wouldn't call the second condition, or if it might sometimes - thanks for explaining why.
  • Richard Tingle
    Richard Tingle almost 11 years
    Its worth mentioning why catching null pointer exceptions is bad practice; exceptions are really really expensive, even a few will really slow your code
  • josefx
    josefx almost 11 years
    @RichardTingle in most cases the cost of an exception is neglible (java uses them all over the place) it is more that the NullpointerException could originate not only from foo but anywhere between try{ and }catch so you might hide a bug by catching it
  • Richard Tingle
    Richard Tingle almost 11 years
    @josefx The cost of doing (almost) anything once is negligible, its obviously only relevant if the section of code its in is a bottle neck; however if it is then its likely to be the cause. I collected some data in response to this question stackoverflow.com/questions/16320014/โ€ฆ. Obviously its also a bad idea for the reasons you mention (any many others besides). Possibly I should have said "one of the reasons" rather than "the reason"
  • matbrgz
    matbrgz almost 10 years
    @RichardTingle exceptions are not as expensive as they used to be (especially if you do not need to inspect the stack trace). Except for that I agree - the reason for me, however, is that exceptions break the program flow as expected by a reader.
  • KrishPrabakar
    KrishPrabakar about 9 years
    Somehow SO doesn't allow me to add import java.util.Objects; line into the code, so putting it in comment here.
  • KrishPrabakar
    KrishPrabakar about 9 years
    In case of Java 8 you can try using Optional class.
  • Xaerxess
    Xaerxess over 8 years
    The second snippet throws NPE when foo is null.
  • Cyril Deba
    Cyril Deba over 8 years
    Xaerxess, you're right, I removed the code snippet with the possible NPE
  • Marcel
    Marcel over 7 years
    Will throw a NullPointer if it is Null
  • Maksim
    Maksim over 7 years
    if you do not have an access to the commons apache library which part of the library were you referring to?
  • khelwood
    khelwood almost 4 years
    (foo = null) does not evaluate to true.
  • khelwood
    khelwood almost 4 years
    (obj = null) does not evaluate to true.
  • Ahmed Hamed
    Ahmed Hamed almost 4 years
    Yes because you are using the short-circuit operand && so it won't finish the whole expression
  • jave.web
    jave.web over 3 years
    @Arty-fishL that's always a good question since it's language dependent - USUALLY C-like languages tend to have short-circuit-left-to-right, but that's not the case for all languages, better always check first ;)
  • darw
    darw over 3 years
    This recommendation is only applicable to C/C++, but not to Java. In fact, Java's recommendation is just the opposite of that
  • rjmunro
    rjmunro almost 3 years
    Method 3 is what you'd normally do in Python. Rather than "You know the item may be null so it's not an exceptional situation" you could say "You know that in exceptional situations (like a file is missing somewhere) it will be null". I don't know why java developers are so afraid of exceptions. What's the point of adding exceptions capability to the language if you still have to check return values everywhere? Is there a performance penalty from surrounding code with try .. catch? Is there a good reason, or is it just Java style?
  • wobblycogs
    wobblycogs almost 3 years
    @rjmunro Exceptions are expensive in Java at least when compared to a regular return. An exception has to capture a stack trace which is quite expensive although I vaguely remember that was optimised a few years ago for people that did use exceptions for flow of control. In Java it's common for an exception to be used for something exceptional, if you expect to read from a file and it's not there that's an exception. As for the null checking I somewhat agree and Java now has numerous ways of dealing with nulls such as the new Optional class.
  • rjmunro
    rjmunro almost 3 years
    On performance, I'm not interested in the performance of the exception happening - worst case it's a second or 2 before the user gets an error message - I'm interested in the performance of surrounding withtry { ... } catch vs if (foo != null) { ... }. Assuming the value is not null, is the explicit null check faster than the try catch, and does that hold if you e.g. have several things that can be null and you surround the whole thing with the try catch, or need the try catch for other errors and are adding an extra catch?
  • wobblycogs
    wobblycogs almost 3 years
    The null check will be at least a thousand times faster (probably many thousands). For the path of execution to get into the catch block an exception has to have been raised which means generating a stack trace etc etc. I don't know for sure but the null check almost certainly drops to a native instruction so it's as close to instant as you can get. As long as there's no exception raised a try catch block has negligible performance impact.
  • Kevin Crum
    Kevin Crum almost 3 years
    with this method I find myself getting operator && cannot be applied to boolean if (object.getObjectMethod() != null && object.getObjectMethod().getNextThing())
  • Prasanth Rajendran
    Prasanth Rajendran over 2 years
    Welcome to StackOverflow, It will be good if you add some extra code snippets demonstrating your suggestion, which will help the answer seekers to get more insights from your answer
  • bluelurker
    bluelurker about 2 years
    This is available since Java 8.
  • forhadmethun
    forhadmethun about 2 years
    updated the answer :)