[java] Avoiding NullPointerException in Java

I use object != null a lot to avoid NullPointerException.

What is an alternative to:

if (someobject != null) {
    someobject.doCalc();
}

This question is related to java nullpointerexception null

The answer is


Java 8 has introduced a new class Optional in java.util package.

Advantages of Java 8 Optional:

1.) Null checks are not required.
2.) No more NullPointerException at run-time.
3.) We can develop clean and neat APIs.

Optional - A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

For more details find here oracle docs :- https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html


All in all to avoid statement

if (object != null) {
    ....
}
  1. since java 7 you can use Objects methods:

    Objects.isNull(object)

    Objects.nonNull(object)

    Objects.requireNonNull(object)

    Objects.equals(object1, object2)

  2. since java 8 you can use Optional class (when to use)

object.ifPresent(obj -> ...); java 8

object.ifPresentOrElse(obj -> ..., () -> ...); java 9

  1. rely on method contract (JSR 305) and use Find Bugs. Mark your code with annotations @javax.annotation.Nullable and @javax.annotation.Nonnnul. Also Preconditions are available.

    Preconditions.checkNotNull(object);

  2. In special cases (for example for Strings and Collections) you can use apache-commons (or Google guava) utility methods:

public static boolean isEmpty(CharSequence cs) //apache CollectionUtils

public static boolean isEmpty(Collection coll) //apache StringUtils

public static boolean isEmpty(Map map) //apache MapUtils

public static boolean isNullOrEmpty(@Nullable String string) //Guava Strings

  1. When you need to assign default value when null use apache commons lang

public static Object defaultIfNull(Object object, Object defaultValue)


With Java 8 comes the new java.util.Optional class that arguably solves some of the problem. One can at least say that it improves the readability of the code, and in the case of public APIs make the API's contract clearer to the client developer.

They work like that:

An optional object for a given type (Fruit) is created as the return type of a method. It can be empty or contain a Fruit object:

public static Optional<Fruit> find(String name, List<Fruit> fruits) {
   for (Fruit fruit : fruits) {
      if (fruit.getName().equals(name)) {
         return Optional.of(fruit);
      }
   }
   return Optional.empty();
}

Now look at this code where we search a list of Fruit (fruits) for a given Fruit instance:

Optional<Fruit> found = find("lemon", fruits);
if (found.isPresent()) {
   Fruit fruit = found.get();
   String name = fruit.getName();
}

You can use the map() operator to perform a computation on--or extract a value from--an optional object. orElse() lets you provide a fallback for missing values.

String nameOrNull = find("lemon", fruits)
    .map(f -> f.getName())
    .orElse("empty-name");

Of course, the check for null/empty value is still necessary, but at least the developer is conscious that the value might be empty and the risk of forgetting to check is limited.

In an API built from scratch using Optional whenever a return value might be empty, and returning a plain object only when it cannot be null (convention), the client code might abandon null checks on simple object return values...

Of course Optional could also be used as a method argument, perhaps a better way to indicate optional arguments than 5 or 10 overloading methods in some cases.

Optional offers other convenient methods, such as orElse that allow the use of a default value, and ifPresent that works with lambda expressions.

I invite you to read this article (my main source for writing this answer) in which the NullPointerException (and in general null pointer) problematic as well as the (partial) solution brought by Optional are well explained: Java Optional Objects.


If you use (or planning to use) a Java IDE like JetBrains IntelliJ IDEA, Eclipse or Netbeans or a tool like findbugs then you can use annotations to solve this problem.

Basically, you've got @Nullable and @NotNull.

You can use in method and parameters, like this:

@NotNull public static String helloWorld() {
    return "Hello World";
}

or

@Nullable public static String helloWorld() {
    return "Hello World";
}

The second example won't compile (in IntelliJ IDEA).

When you use the first helloWorld() function in another piece of code:

public static void main(String[] args)
{
    String result = helloWorld();
    if(result != null) {
        System.out.println(result);
    }
}

Now the IntelliJ IDEA compiler will tell you that the check is useless, since the helloWorld() function won't return null, ever.

Using parameter

void someMethod(@NotNull someParameter) { }

if you write something like:

someMethod(null);

This won't compile.

Last example using @Nullable

@Nullable iWantToDestroyEverything() { return null; }

Doing this

iWantToDestroyEverything().something();

And you can be sure that this won't happen. :)

It's a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it's not supported by all the compilers.

In IntelliJ IDEA 10.5 and on, they added support for any other @Nullable @NotNull implementations.

See blog post More flexible and configurable @Nullable/@NotNull annotations.


With Java 8 comes the new java.util.Optional class that arguably solves some of the problem. One can at least say that it improves the readability of the code, and in the case of public APIs make the API's contract clearer to the client developer.

They work like that:

An optional object for a given type (Fruit) is created as the return type of a method. It can be empty or contain a Fruit object:

public static Optional<Fruit> find(String name, List<Fruit> fruits) {
   for (Fruit fruit : fruits) {
      if (fruit.getName().equals(name)) {
         return Optional.of(fruit);
      }
   }
   return Optional.empty();
}

Now look at this code where we search a list of Fruit (fruits) for a given Fruit instance:

Optional<Fruit> found = find("lemon", fruits);
if (found.isPresent()) {
   Fruit fruit = found.get();
   String name = fruit.getName();
}

You can use the map() operator to perform a computation on--or extract a value from--an optional object. orElse() lets you provide a fallback for missing values.

String nameOrNull = find("lemon", fruits)
    .map(f -> f.getName())
    .orElse("empty-name");

Of course, the check for null/empty value is still necessary, but at least the developer is conscious that the value might be empty and the risk of forgetting to check is limited.

In an API built from scratch using Optional whenever a return value might be empty, and returning a plain object only when it cannot be null (convention), the client code might abandon null checks on simple object return values...

Of course Optional could also be used as a method argument, perhaps a better way to indicate optional arguments than 5 or 10 overloading methods in some cases.

Optional offers other convenient methods, such as orElse that allow the use of a default value, and ifPresent that works with lambda expressions.

I invite you to read this article (my main source for writing this answer) in which the NullPointerException (and in general null pointer) problematic as well as the (partial) solution brought by Optional are well explained: Java Optional Objects.


Another alternative to the != null check is (if you can't get rid of it design-wise):

Optional.ofNullable(someobject).ifPresent(someobject -> someobject.doCalc());

or

Optional.ofNullable(someobject).ifPresent(SomeClass::doCalc);

With SomeClass being someobject's type.

You can't get a return value back from doCalc() though, so only useful for void methods.


public class Null {

public static void main(String[] args) {
    String str1 = null;
    String str2 = "";

    if(isNullOrEmpty(str1))
        System.out.println("First string is null or empty.");
    else
        System.out.println("First string is not null or empty.");

    if(isNullOrEmpty(str2))
        System.out.println("Second string is null or empty.");
    else
        System.out.println("Second string is not null or empty.");
}

public static boolean isNullOrEmpty(String str) {
    if(str != null && !str.isEmpty())
        return false;
    return true;
}
}

Output

str1 is null or empty.
str2 is null or empty.

In the above program, we've two strings str1 and str2. str1 contains null value and str2 is an empty string.

We've also created a function isNullOrEmpty() which checks, as the name suggests, whether the string is null or empty. It checks it using a null check using != null and isEmpty() method of string.

In plain terms, if a string isn't a null and isEmpty() returns false, it's not either null or empty. Else, it is.

However, the above program doesn't return empty if a string contains only whitespace characters (spaces). Technically, isEmpty() sees it contains spaces and returns false. For string with spaces, we use the string method trim() to trim out all the leading and trailing whitespace characters.


OK, I now this has been technically answered a million times but I have to say this because this is an un-ending discussion with Java programmers.

Sorry but I disagree will almost all of above. The reason we have to be testing for null in Java is because must Java programmers don’t know how to handle memory.

I say this because I have a long experience programming in C++ and we don’t do this. In other words, you don’t need to. And note that, in Java, if you hit a dangling pointer you get a normal exception; in C++ this exception normally is not caught and terminates the program.

Don’t want to do this? Then follow some simple rules ala C/C++.

Don’t instantiate things so easily, think that every "new" can get you in lots of trouble and FOLLOW these simple rules.

A class shall access memory in only 3 ways ->

  1. It can "HAVE" class members, and they will follow these rules:

    1. ALL "HAS" members are created "new" in the constructor.
    2. You will close /de allocate in destructor or equivalent close() function in Java for that same class and in NO other.

This means that you need to have in mind (just like Java does) who is the owner or parent of each resource and respect that ownership. An object is only deleted by the class who created it. Also ->

  1. Some members will be "USED" but not own or "HAVE". This are "OWN" in another class and passed as arguments to the constructor. Since these are owned by another class, we will NEVER delete or close this, only the parent can.

  2. A method in a class can also instantiate local objects for internal use which will NEVER pass out side of the class, or they should have been normal "has" objects.

Finally for all this to work, you need to have a disciplined design with classes in hierarchy form and making no cycles.

Under this design, AND following the above rules, there is no way that a child class in a hierarchy design will ever access a pointer which was destroyed, because that means that a parent was destroyed before a child, which the hierarchical acyclic design will not allow it.

Finally, also remember when starting your system you should build from top to bottom of the hierarchy and destroy bottom to top. You will never have a null pointer anywhere, or someone is violating the rules.


I follow below guidelines to avoid null checks.

  1. Avoid lazy initialization of member variables as much as possible. Initialize the variables in declaration itself. This will handle NullPointerExceptions.

  2. Decide on mutability of member variables early in the cycle. Use language constructs like final keyword effectively.

  3. If you know that augments for method won't be changed, declare them as final.

  4. Limit the mutation of data as much as possible. Some variables can be created in a constructor and can never be changed. Remove public setter methods unless they are really required.

    E.g. Assume that one class in your application (A.java) is maintaining a collection like HashMap. Don't provide public getter method in A.java and allow B.java to directly add an element in Map. Instead provide an API in A.java, which adds an element into collection.

    // Avoid
    a.getMap().put(key,value)
    
    //recommended
    
    public void addElement(Object key, Object value){
           // Have null checks for both key and value here : single place
           map.put(key,value);
    }
    
  5. And finally, use try{} catch{} finally{} blocks at right places effectively.


I highly disregard answers that suggest using the null objects in every situation. This pattern may break the contract and bury problems deeper and deeper instead of solving them, not mentioning that used inappropriately will create another pile of boilerplate code that will require future maintenance.

In reality if something returned from a method can be null and the calling code has to make decision upon that, there should an earlier call that ensures the state.

Also keep in mind, that null object pattern will be memory hungry if used without care. For this - the instance of a NullObject should be shared between owners, and not be an unigue instance for each of these.

Also I would not recommend using this pattern where the type is meant to be a primitive type representation - like mathematical entities, that are not scalars: vectors, matrices, complex numbers and POD(Plain Old Data) objects, which are meant to hold state in form of Java built-in types. In the latter case you would end up calling getter methods with arbitrary results. For example what should a NullPerson.getName() method return?

It's worth considering such cases in order to avoid absurd results.


Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections

Example:

String foo;
...
if( StringUtils.isBlank( foo ) ) {
   ///do something
}

or (depending on what you need to check):

String foo;
...
if( StringUtils.isEmpty( foo ) ) {
   ///do something
}

The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.

Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)

public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
    Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
    return read(new StringReader(xml), true, validationEventHandler);
}

And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar)

Example on how to use this static classf from spring(org.springframework.util.Assert)

Assert.notNull(validationEventHandler,"ValidationHandler not Injected");

Guava, a very useful core library by Google, has a nice and useful API to avoid nulls. I find UsingAndAvoidingNullExplained very helpful.

As explained in the wiki:

Optional<T> is a way of replacing a nullable T reference with a non-null value. An Optional may either contain a non-null T reference (in which case we say the reference is "present"), or it may contain nothing (in which case we say the reference is "absent"). It is never said to "contain null."

Usage:

Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5

Only for this situation -

Not checking if a variable is null before invoking an equals method (a string compare example below):

if ( foo.equals("bar") ) {
 // ...
}

will result in a NullPointerException if foo doesn't exist.

You can avoid that if you compare your Strings like this:

if ( "bar".equals(foo) ) {
 // ...
}

I've tried the NullObjectPattern but for me is not always the best way to go. There are sometimes when a "no action" is not appropiate.

NullPointerException is a Runtime exception that means it's developers fault and with enough experience it tells you exactly where is the error.

Now to the answer:

Try to make all your attributes and its accessors as private as possible or avoid to expose them to the clients at all. You can have the argument values in the constructor of course, but by reducing the scope you don't let the client class pass an invalid value. If you need to modify the values, you can always create a new object. You check the values in the constructor only once and in the rest of the methods you can be almost sure that the values are not null.

Of course, experience is the better way to understand and apply this suggestion.

Byte!


The way to avoid unnecessary null-checks is simple to state:

You need to know which variables can be null, and which cannot, and you need to be confident about which category a given variable fall into.

But, although it can be stated simply enough, achieving it is harder. The key lies in the confident part, because how can you be sure that a variable can't be null?

There are no quick-fix, easy answers to this, but here are some pointers:

  1. Clean code. The most important thing for being able to reason about the behaviour of a piece of code is that it is written in a matter that is easy to understand. Name your variables based on what they represent, name your methods after what they do, apply the Single responsibility principle (the S in SOLID: http://en.wikipedia.org/wiki/SOLID_(object-oriented_design), it means that each piece of code should have a single responsibility, and do this and nothing else). Once your code is clean, it is much easier to reason about it, also across multiple tiers/layers of code. With messy code, trying to understand what a method does might make you forget why you are reading the method in the first place. (Tip: Read "Clean Code" by Robert C. Martin)

  2. Avoid returning null values. If a null value would keep your program from functioning correctly, throw an exception instead (make sure to add the appropriate error-handling.) Cases where returning a null value might be acceptable is for instance trying to fetch an object from the database. In these cases, write code that handles the null values, and make a note behind your ear that here we have something that might return null. Handle returned null values as close to the caller of the method returning null as possible (don't just blindly pass it back up the call-chain.)

  3. Never EVER pass explicit null values as parameters (at least not across classes). If you are ever in a position where passing a null-parameter is the only option, creating a new method that does not have this parameter is the way to go.

  4. Validate your input! Identify the "entry-points" to your application. They can everything from webservices, REST-services, remote EJB classes, controllers, etc. For each method in these entry-points, ask yourself: "Will this method execute correctly if this parameter is null?" If the answer is no, add Validate.notNull(someParam, "Can't function when someParam is null!");. This will throw an IllegalArgumentException if the required parameter is missing. The good thing about this type of validation in the entry-points, is that you can then easily assume in the code being executed from the entry-point, that this variable will never be null! Also, if this fails, being at the entry-point, debugging is made a lot easier than it would if you just got a NullPointerException deep down in your code, since a failure like this can only mean one thing: The client didn't send you all the required information. In most cases you want to validate all input parameters, if you find yourself in a position where you need to allow a lot of null-values, it might be a sign of a badly designed interface, which needs refactoring/additions to suite the needs of the clients.

  5. When working with Collections, return an empty one rather than null!

  6. When working with a database, utilize not null-constraints. In that way, you'll know that a value read from the database cannot be null, and you won't have to check for it.

  7. Structure your code and stick with it. Doing this allows you to make assumptions about the behaviour of the code, for instance if all input to your application is validated, then you can assume that these values will never be null.

  8. If you are not already doing it, write automated tests of your code. By writing tests, you will reason about your code, and you will also become more confident that it does what it's supposed to. Also, automated tests guards you from blunders during refactoring, by letting you know immediatly that this piece of code is not doing what it used to.

You still have to null-check of course, but it can trimmed down to the bare minimum (i.e. the situation where know you might be getting a null-value, instead of everywhere just to be sure.) When it comes to null-checks, i actually prefer to use the ternary operator (but use with care, when you start nesting them they come really messy.)

public String nullSafeToString(final Object o) {
    return o != null ? o.toString() : "null";
}

One more alternative:

The following simple function helps to hide the null-check (I don't know why, but I haven't found it as part of the same common library):

public static <T> boolean isNull(T argument) {
    return (argument == null);
}

You could now write

if (!isNull(someobject)) {
    someobject.doCalc();
}

which is IMO a better way of expressing != null.


This is the most common error occurred for most of the developers.

We have number of ways to handle this.

Approach 1:

org.apache.commons.lang.Validate //using apache framework

notNull(Object object, String message)

Approach 2:

if(someObject!=null){ // simply checking against null
}

Approach 3:

@isNull @Nullable  // using annotation based validation

Approach 4:

// by writing static method and calling it across whereever we needed to check the validation

static <T> T isNull(someObject e){  
   if(e == null){
      throw new NullPointerException();
   }
   return e;
}

Here is my approach ..

class MyObjectHandler
{
public static final int EXCEPTION = (-3);
public static final int INACCESSIBLE = (-2);

public static int doSomething (MyObject obj, MyObjectParameter [] input)
{
    int returnValue= 0;

    try
    {
        if (obj != null)
        {
            returnValue = obj.doSomething(input);
        }
        else
        {
            returnValue = MyObjectHandler.INACCESSIBLE;
        }
    }
    catch (Exception e)
    {
        e.printStack();
        returnValue = MyObjectHandler.EXCEPTION;
    }
    finally
    {
        return returnValue;
    }
}

..

}

Then your code will be just like:

import xx.xx.xx.MyObjectHandler;
import xx.xx.xx.MyObjectParameter;

class Test
{

    public static void main ()
    {

        MyObject obj = null;

        MyObjectHandler.doSomething(obj, null);

    }

    ..

}

Sometimes, you have methods that operate on its parameters that define a symmetric operation:

a.f(b); <-> b.f(a);

If you know b can never be null, you can just swap it. It is most useful for equals: Instead of foo.equals("bar"); better do "bar".equals(foo);.


If undefined values are not permitted:

You might configure your IDE to warn you about potential null dereferencing. E.g. in Eclipse, see Preferences > Java > Compiler > Errors/Warnings/Null analysis.

If undefined values are permitted:

If you want to define a new API where undefined values make sense, use the Option Pattern (may be familiar from functional languages). It has the following advantages:

  • It is stated explicitly in the API whether an input or output exists or not.
  • The compiler forces you to handle the "undefined" case.
  • Option is a monad, so there is no need for verbose null checking, just use map/foreach/getOrElse or a similar combinator to safely use the value (example).

Java 8 has a built-in Optional class (recommended); for earlier versions, there are library alternatives, for example Guava's Optional or FunctionalJava's Option. But like many functional-style patterns, using Option in Java (even 8) results in quite some boilerplate, which you can reduce using a less verbose JVM language, e.g. Scala or Xtend.

If you have to deal with an API which might return nulls, you can't do much in Java. Xtend and Groovy have the Elvis operator ?: and the null-safe dereference operator ?., but note that this returns null in case of a null reference, so it just "defers" the proper handling of null.


I've tried the NullObjectPattern but for me is not always the best way to go. There are sometimes when a "no action" is not appropiate.

NullPointerException is a Runtime exception that means it's developers fault and with enough experience it tells you exactly where is the error.

Now to the answer:

Try to make all your attributes and its accessors as private as possible or avoid to expose them to the clients at all. You can have the argument values in the constructor of course, but by reducing the scope you don't let the client class pass an invalid value. If you need to modify the values, you can always create a new object. You check the values in the constructor only once and in the rest of the methods you can be almost sure that the values are not null.

Of course, experience is the better way to understand and apply this suggestion.

Byte!


Null object pattern can be used as a solution for this problem. For that, the class of the someObject should be modified.

public abstract class SomeObject {
   public abstract boolean isNil();
}

public class NullObject extends SomeObject {
   @Override
   public boolean isNil() {
      return true;
   }
}
public class RealObject extends SomeObject {
   @Override
   public boolean isNil() {
      return false;
   }
}

Now istead of checking,

 if (someobject != null) {
    someobject.doCalc();
}

We can use,

if (!someObject.isNil()) {
   someobject.doCalc();
}

Reference : https://www.tutorialspoint.com/design_pattern/null_object_pattern.htm


In addition to using assert you can use the following:

if (someobject == null) {
    // Handle null here then move on.
}

This is slightly better than:

if (someobject != null) {
    .....
    .....



    .....
}

The best way to avoid Null Checks in Java, is to properly handle and use exceptions. Null Checks in my experience have become more common and required as you move closer to the front-end, because it's closer to the user who may supply invalid information through the UI (such as, no value, being submitted for a field).

One may argue that you should be able to control what the UI is doing, lest you forget most UI is done through a third party library of some kind, which for example, may return either NULL or an Empty String for a blank text box, depending on the situation or the library.

You can combine the two like this:

try
{
  myvar = get_user_supplied_value(); 
  if (!myvar || myvar.length() == 0) { alert_the_user_somehow(); return; };

  process_user_input(myvar);
} catch (Exception ex) {
  handle_exception(ex);
}

Another approach people take is to say:

if (myvar && myvar.length() > 0)  { };

You could also throw an exception (which is what I prefer)

if (!myvar || myvar.length() == 0) {
 throw new Exception("You must supply a name!");
};

But that's up to you.


Null is not a 'problem'. It is an integral part of a complete modeling tool set. Software aims to model the complexity of the world and null bears its burden. Null indicates 'No data' or 'Unknown' in Java and the like. So it is appropriate to use nulls for these purposes. I don't prefer the 'Null object' pattern; I think it rise the 'who will guard the guardians' problem.
If you ask me what is the name of my girlfriend I'll tell you that I have no girlfriend. In the Java language I'll return null. An alternative would be to throw meaningful exception to indicate some problem that can't be (or don't want to be) solved right there and delegate it somewhere higher in the stack to retry or report data access error to the user.

  1. For an 'unknown question' give 'unknown answer'. (Be null-safe where this is correct from business point of view) Checking arguments for null once inside a method before usage relieves multiple callers from checking them before a call.

    public Photo getPhotoOfThePerson(Person person) {
        if (person == null)
            return null;
        // Grabbing some resources or intensive calculation
        // using person object anyhow.
    }
    

    Previous leads to normal logic flow to get no photo of a non-existent girlfriend from my photo library.

    getPhotoOfThePerson(me.getGirlfriend())
    

    And it fits with new coming Java API (looking forward)

    getPhotoByName(me.getGirlfriend()?.getName())
    

    While it is rather 'normal business flow' not to find photo stored into the DB for some person, I used to use pairs like below for some other cases

    public static MyEnum parseMyEnum(String value); // throws IllegalArgumentException
    public static MyEnum parseMyEnumOrNull(String value);
    

    And don't loathe to type <alt> + <shift> + <j> (generate javadoc in Eclipse) and write three additional words for you public API. This will be more than enough for all but those who don't read documentation.

    /**
     * @return photo or null
     */
    

    or

    /**
     * @return photo, never null
     */
    
  2. This is rather theoretical case and in most cases you should prefer java null safe API (in case it will be released in another 10 years), but NullPointerException is subclass of an Exception. Thus it is a form of Throwable that indicates conditions that a reasonable application might want to catch (javadoc)! To use the first most advantage of exceptions and separate error-handling code from 'regular' code (according to creators of Java) it is appropriate, as for me, to catch NullPointerException.

    public Photo getGirlfriendPhoto() {
        try {
            return appContext.getPhotoDataSource().getPhotoByName(me.getGirlfriend().getName());
        } catch (NullPointerException e) {
            return null;
        }
    }
    

    Questions could arise:

    Q. What if getPhotoDataSource() returns null?
    A. It is up to business logic. If I fail to find a photo album I'll show you no photos. What if appContext is not initialized? This method's business logic puts up with this. If the same logic should be more strict then throwing an exception it is part of the business logic and explicit check for null should be used (case 3). The new Java Null-safe API fits better here to specify selectively what implies and what does not imply to be initialized to be fail-fast in case of programmer errors.

    Q. Redundant code could be executed and unnecessary resources could be grabbed.
    A. It could take place if getPhotoByName() would try to open a database connection, create PreparedStatement and use the person name as an SQL parameter at last. The approach for an unknown question gives an unknown answer (case 1) works here. Before grabbing resources the method should check parameters and return 'unknown' result if needed.

    Q. This approach has a performance penalty due to the try closure opening.
    A. Software should be easy to understand and modify firstly. Only after this, one could think about performance, and only if needed! and where needed! (source), and many others).

    PS. This approach will be as reasonable to use as the separate error-handling code from "regular" code principle is reasonable to use in some place. Consider the next example:

    public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {
        try {
            Result1 result1 = performSomeCalculation(predicate);
            Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());
            Result3 result3 = performThirdCalculation(result2.getSomeProperty());
            Result4 result4 = performLastCalculation(result3.getSomeProperty());
            return result4.getSomeProperty();
        } catch (NullPointerException e) {
            return null;
        }
    }
    
    public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {
        SomeValue result = null;
        if (predicate != null) {
            Result1 result1 = performSomeCalculation(predicate);
            if (result1 != null && result1.getSomeProperty() != null) {
                Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());
                if (result2 != null && result2.getSomeProperty() != null) {
                    Result3 result3 = performThirdCalculation(result2.getSomeProperty());
                    if (result3 != null && result3.getSomeProperty() != null) {
                        Result4 result4 = performLastCalculation(result3.getSomeProperty());
                        if (result4 != null) {
                            result = result4.getSomeProperty();
                        }
                    }
                }
            }
        }
        return result;
    }
    

    PPS. For those fast to downvote (and not so fast to read documentation) I would like to say that I've never caught a null-pointer exception (NPE) in my life. But this possibility was intentionally designed by the Java creators because NPE is a subclass of Exception. We have a precedent in Java history when ThreadDeath is an Error not because it is actually an application error, but solely because it was not intended to be caught! How much NPE fits to be an Error than ThreadDeath! But it is not.

  3. Check for 'No data' only if business logic implies it.

    public void updatePersonPhoneNumber(Long personId, String phoneNumber) {
        if (personId == null)
            return;
        DataSource dataSource = appContext.getStuffDataSource();
        Person person = dataSource.getPersonById(personId);
        if (person != null) {
            person.setPhoneNumber(phoneNumber);
            dataSource.updatePerson(person);
        } else {
            Person = new Person(personId);
            person.setPhoneNumber(phoneNumber);
            dataSource.insertPerson(person);
        }
    }
    

    and

    public void updatePersonPhoneNumber(Long personId, String phoneNumber) {
        if (personId == null)
            return;
        DataSource dataSource = appContext.getStuffDataSource();
        Person person = dataSource.getPersonById(personId);
        if (person == null)
            throw new SomeReasonableUserException("What are you thinking about ???");
        person.setPhoneNumber(phoneNumber);
        dataSource.updatePerson(person);
    }
    

    If appContext or dataSource is not initialized unhandled runtime NullPointerException will kill current thread and will be processed by Thread.defaultUncaughtExceptionHandler (for you to define and use your favorite logger or other notification mechanizm). If not set, ThreadGroup#uncaughtException will print stacktrace to system err. One should monitor application error log and open Jira issue for each unhandled exception which in fact is application error. Programmer should fix bug somewhere in initialization stuff.


One Option you have

  • Use checker framework's @RequiresNonNull on methods. for ex you get this if you call a method annotated as such, with a null argument. It will fail during compile, even before your code runs! since at runtime it will be NullPointerException

    @RequiresNonNull(value = { "#1" })
    static void check( Boolean x) {
        if (x) System.out.println("true");
        else System.out.println("false");
    }
    
    public static void main(String[] args) {
    
    
        check(null);
    
    }
    

gets

[ERROR] found   : null
[ERROR] required: @Initialized @NonNull Boolean
[ERROR] -> [Help 1]

There are other methods like Use Java 8's Optional, Guava Annotations, Null Object pattern etc. Does not matter as long as you obtain your goal of avoiding !=null


public static <T> T ifNull(T toCheck, T ifNull) {
    if (toCheck == null) {
           return ifNull;
    }
    return toCheck;
}

Only for this situation -

Not checking if a variable is null before invoking an equals method (a string compare example below):

if ( foo.equals("bar") ) {
 // ...
}

will result in a NullPointerException if foo doesn't exist.

You can avoid that if you compare your Strings like this:

if ( "bar".equals(foo) ) {
 // ...
}

Wow, I almost hate to add another answer when we have 57 different ways to recommend the NullObject pattern, but I think that some people interested in this question may like to know that there is a proposal on the table for Java 7 to add "null-safe handling"—a streamlined syntax for if-not-equal-null logic.

The example given by Alex Miller looks like this:

public String getPostcode(Person person) {  
  return person?.getAddress()?.getPostcode();  
}  

The ?. means only de-reference the left identifier if it is not null, otherwise evaluate the remainder of the expression as null. Some people, like Java Posse member Dick Wall and the voters at Devoxx really love this proposal, but there is opposition too, on the grounds that it will actually encourage more use of null as a sentinel value.


Update: An official proposal for a null-safe operator in Java 7 has been submitted under Project Coin. The syntax is a little different than the example above, but it's the same notion.


Update: The null-safe operator proposal didn't make it into Project Coin. So, you won't be seeing this syntax in Java 7.


I like articles from Nat Pryce. Here are the links:

In the articles there is also a link to a Git repository for a Java Maybe Type which I find interesting, but I don't think it alone could decrease the checking code bloat. After doing some research on the Internet, I think != null code bloat could be decreased mainly by careful design.


public class Null {

public static void main(String[] args) {
    String str1 = null;
    String str2 = "";

    if(isNullOrEmpty(str1))
        System.out.println("First string is null or empty.");
    else
        System.out.println("First string is not null or empty.");

    if(isNullOrEmpty(str2))
        System.out.println("Second string is null or empty.");
    else
        System.out.println("Second string is not null or empty.");
}

public static boolean isNullOrEmpty(String str) {
    if(str != null && !str.isEmpty())
        return false;
    return true;
}
}

Output

str1 is null or empty.
str2 is null or empty.

In the above program, we've two strings str1 and str2. str1 contains null value and str2 is an empty string.

We've also created a function isNullOrEmpty() which checks, as the name suggests, whether the string is null or empty. It checks it using a null check using != null and isEmpty() method of string.

In plain terms, if a string isn't a null and isEmpty() returns false, it's not either null or empty. Else, it is.

However, the above program doesn't return empty if a string contains only whitespace characters (spaces). Technically, isEmpty() sees it contains spaces and returns false. For string with spaces, we use the string method trim() to trim out all the leading and trailing whitespace characters.


I like articles from Nat Pryce. Here are the links:

In the articles there is also a link to a Git repository for a Java Maybe Type which I find interesting, but I don't think it alone could decrease the checking code bloat. After doing some research on the Internet, I think != null code bloat could be decreased mainly by careful design.


I follow below guidelines to avoid null checks.

  1. Avoid lazy initialization of member variables as much as possible. Initialize the variables in declaration itself. This will handle NullPointerExceptions.

  2. Decide on mutability of member variables early in the cycle. Use language constructs like final keyword effectively.

  3. If you know that augments for method won't be changed, declare them as final.

  4. Limit the mutation of data as much as possible. Some variables can be created in a constructor and can never be changed. Remove public setter methods unless they are really required.

    E.g. Assume that one class in your application (A.java) is maintaining a collection like HashMap. Don't provide public getter method in A.java and allow B.java to directly add an element in Map. Instead provide an API in A.java, which adds an element into collection.

    // Avoid
    a.getMap().put(key,value)
    
    //recommended
    
    public void addElement(Object key, Object value){
           // Have null checks for both key and value here : single place
           map.put(key,value);
    }
    
  5. And finally, use try{} catch{} finally{} blocks at right places effectively.


I've tried the NullObjectPattern but for me is not always the best way to go. There are sometimes when a "no action" is not appropiate.

NullPointerException is a Runtime exception that means it's developers fault and with enough experience it tells you exactly where is the error.

Now to the answer:

Try to make all your attributes and its accessors as private as possible or avoid to expose them to the clients at all. You can have the argument values in the constructor of course, but by reducing the scope you don't let the client class pass an invalid value. If you need to modify the values, you can always create a new object. You check the values in the constructor only once and in the rest of the methods you can be almost sure that the values are not null.

Of course, experience is the better way to understand and apply this suggestion.

Byte!


Guava, a very useful core library by Google, has a nice and useful API to avoid nulls. I find UsingAndAvoidingNullExplained very helpful.

As explained in the wiki:

Optional<T> is a way of replacing a nullable T reference with a non-null value. An Optional may either contain a non-null T reference (in which case we say the reference is "present"), or it may contain nothing (in which case we say the reference is "absent"). It is never said to "contain null."

Usage:

Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5

Another suggestion is to program defensively - where your classes/functions provide default values that are known and safe, and where null is reserved for true errors/exceptions.

For example, instead of functions that return Strings returning null when there is a problem (say converting a number to a string), have them return an empty String (""). You still have to test the return value before proceeding, but there would be no special cases for exceptions. An additional benefit of this style of programming is that your program will be able to differentiate and respond accordingly between normal operations and exceptions.


First of all, we can't really remove all null conditions. We can reduce them using @NotNull and @Nullable annotations (as mentioned already). But this needs to be backed by some framework. This is where OVal can help.

The basic idea is object/parameters/constructor should always satisfy preconditions. You can have a whole lot of preconditions such as Nullable, NotNull and OVal would take care that an object should be in a consistent state when invoked.

I guess OVal internally uses AspectJ to validate the preconditions.

@Guarded
public class BusinessObject
{
  public BusinessObject(@NotNull String name)
  {
    this.name = name;
  }

  ...
}

For example,

// Throws a ConstraintsViolatedException because parameter name is null
BusinessObject bo = new BusinessObject(null);

Rather than Null Object Pattern -- which has its uses -- you might consider situations where the null object is a bug.

When the exception is thrown, examine the stack trace and work through the bug.


With Java 8, you could pass a supplier to a helper method like below,

if(CommonUtil.resolve(()-> a.b().c()).isPresent()) {

}

Above replaces boiler plate code like below,

if(a!=null && a.b()!=null && a.b().c()!=null) {

}

//CommonUtil.java

 public static <T> Optional<T> resolve(Supplier<T> resolver) {
        try {
            T result = resolver.get();
            return Optional.ofNullable(result);
        } catch (NullPointerException var2) {
            return Optional.empty();
        }
    }

Kotlin with null safety is elegant alternative, but it means a larger change.


You can use FindBugs. They also have an Eclipse plugin) that helps you find duplicate null checks (among other things), but keep in mind that sometimes you should opt for defensive programming. There is also Contracts for Java which may be helpful.


Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections

Example:

String foo;
...
if( StringUtils.isBlank( foo ) ) {
   ///do something
}

or (depending on what you need to check):

String foo;
...
if( StringUtils.isEmpty( foo ) ) {
   ///do something
}

The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.

Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)

public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
    Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
    return read(new StringReader(xml), true, validationEventHandler);
}

And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar)

Example on how to use this static classf from spring(org.springframework.util.Assert)

Assert.notNull(validationEventHandler,"ValidationHandler not Injected");

I prefer this

public void simpleFunc(SomeObject someObject){
    someObject = someObject != null ? someObject : new SomeObject(null);
    someObject.doSomething();
}

Of course in my example SomeObject handles gracefully a null parameter. For example logging such event and doing nothing more.


In Java 8 you can use type T for local-variable/field/method-argument/method-return-type if it never assigned null (and do not check for null) or type Optional<T> if it can be null. Then use method map for processing T -> and method flatMap for processing T -> Optional<R>:

class SomeService {
    @Inject
    private CompanyDao companyDao;

    // return Optional<String>
    public Optional<String> selectCeoCityByCompanyId0(int companyId) {
        return companyDao.selectById(companyId)
                .map(Company::getCeo)
                .flatMap(Person::getHomeAddress)
                .flatMap(Address::getCity);
    }

    // return String + default value
    public String selectCeoCityByCompanyId1(int companyId) {
        return companyDao.selectById(companyId)
                .map(Company::getCeo)
                .flatMap(Person::getHomeAddress)
                .flatMap(Address::getCity)
                .orElse("UNKNOWN");
    }

    // return String + exception
    public String selectCeoCityByCompanyId2(int companyId) throws NoSuchElementException {
        return companyDao.selectById(companyId)
                .map(Company::getCeo)
                .flatMap(Person::getHomeAddress)
                .flatMap(Address::getCity)
                .orElseThrow(NoSuchElementException::new);
    }
}

interface CompanyDao {
    // real situation: no company for such id -> use Optional<Company> 
    Optional<Company> selectById(int id);
}

class Company {
    // company always has ceo -> use Person 
    Person ceo;
    public Person getCeo() {return ceo;}
}

class Person {
    // person always has name -> use String
    String firstName;
    // person can be without address -> use Optional<Address>
    Optional<Address> homeAddress = Optional.empty();

    public String getFirstName() {return firstName;}   
    public Optional<Address> getHomeAddress() {return homeAddress;}
}

class Address {
    //  address always contains country -> use String
    String country;
    //  city field is optional -> use Optional<String>
    Optional<String> city = Optional.empty();

    String getCountry() {return country;}    
    Optional<String> getCity() {return city;}
}

Probably the best alternative for Java 8 or newer is to use the Optional class.

Optional stringToUse = Optional.of("optional is there");
stringToUse.ifPresent(System.out::println);

This is especially handy for long chains of possible null values. Example:

Optional<Integer> i = Optional.ofNullable(wsObject.getFoo())
    .map(f -> f.getBar())
    .map(b -> b.getBaz())
    .map(b -> b.getInt());

Example on how to throw exception on null:

Optional optionalCarNull = Optional.ofNullable(someNull);
optionalCarNull.orElseThrow(IllegalStateException::new);

Java 7 introduced the Objects.requireNonNull method which can be handy when something should be checked for non-nullness. Example:

String lowerVal = Objects.requireNonNull(someVar, "input cannot be null or empty").toLowerCase();

May I answer it more generally!

We usually face this issue when the methods get the parameters in the way we not expected (bad method call is programmer's fault). For example: you expect to get an object, instead you get a null. You expect to get an String with at least one character, instead you get an empty String ...

So there is no difference between:

if(object == null){
   //you called my method badly!

}

or

if(str.length() == 0){
   //you called my method badly again!
}

They both want to make sure that we received valid parameters, before we do any other functions.

As mentioned in some other answers, to avoid above problems you can follow the Design by contract pattern. Please see http://en.wikipedia.org/wiki/Design_by_contract.

To implement this pattern in java, you can use core java annotations like javax.annotation.NotNull or use more sophisticated libraries like Hibernate Validator.

Just a sample:

getCustomerAccounts(@NotEmpty String customerId,@Size(min = 1) String accountType)

Now you can safely develop the core function of your method without needing to check input parameters, they guard your methods from unexpected parameters.

You can go a step further and make sure that only valid pojos could be created in your application. (sample from hibernate validator site)

public class Car {

   @NotNull
   private String manufacturer;

   @NotNull
   @Size(min = 2, max = 14)
   private String licensePlate;

   @Min(2)
   private int seatCount;

   // ...
}

Another suggestion is to program defensively - where your classes/functions provide default values that are known and safe, and where null is reserved for true errors/exceptions.

For example, instead of functions that return Strings returning null when there is a problem (say converting a number to a string), have them return an empty String (""). You still have to test the return value before proceeding, but there would be no special cases for exceptions. An additional benefit of this style of programming is that your program will be able to differentiate and respond accordingly between normal operations and exceptions.


I find Guava Preconditions to be very useful in this case. I don't like leaving nulls to null pointer exception since the only way to understand an NPE is by locating the line number. Line numbers in production version and development version can be different.

Using Guava Preconditions, I can check null parameters and define a meaningful exception message in one line.

For example,

Preconditions.checkNotNull(paramVal, "Method foo received null paramVal");

Since Java 7 the class java.util.Objects exists.

But since Java 8, you can use Objects.isNull(var) and Objects.nonNull(var) methods of Objects class to do the null pointer check.

For example,

String var1 = null;
Date var2 = null;
Long var3 = null;

if(Objects.isNull(var1) && Objects.isNull(var2) && Objects.isNull(var3))
    System.out.println("All Null");
else if (Objects.nonNull(var1) && Objects.nonNull(var2) && Objects.nonNull(var3))
    System.out.println("All Not Null");

The Google collections framework offers a good and elegant way to achieve the null check.

There is a method in a library class like this:

static <T> T checkNotNull(T e) {
   if (e == null) {
      throw new NullPointerException();
   }
   return e;
}

And the usage is (with import static):

...
void foo(int a, Person p) {
   if (checkNotNull(p).getAge() > a) {
      ...
   }
   else {
      ...
   }
}
...

Or in your example:

checkNotNull(someobject).doCalc();

The way to avoid unnecessary null-checks is simple to state:

You need to know which variables can be null, and which cannot, and you need to be confident about which category a given variable fall into.

But, although it can be stated simply enough, achieving it is harder. The key lies in the confident part, because how can you be sure that a variable can't be null?

There are no quick-fix, easy answers to this, but here are some pointers:

  1. Clean code. The most important thing for being able to reason about the behaviour of a piece of code is that it is written in a matter that is easy to understand. Name your variables based on what they represent, name your methods after what they do, apply the Single responsibility principle (the S in SOLID: http://en.wikipedia.org/wiki/SOLID_(object-oriented_design), it means that each piece of code should have a single responsibility, and do this and nothing else). Once your code is clean, it is much easier to reason about it, also across multiple tiers/layers of code. With messy code, trying to understand what a method does might make you forget why you are reading the method in the first place. (Tip: Read "Clean Code" by Robert C. Martin)

  2. Avoid returning null values. If a null value would keep your program from functioning correctly, throw an exception instead (make sure to add the appropriate error-handling.) Cases where returning a null value might be acceptable is for instance trying to fetch an object from the database. In these cases, write code that handles the null values, and make a note behind your ear that here we have something that might return null. Handle returned null values as close to the caller of the method returning null as possible (don't just blindly pass it back up the call-chain.)

  3. Never EVER pass explicit null values as parameters (at least not across classes). If you are ever in a position where passing a null-parameter is the only option, creating a new method that does not have this parameter is the way to go.

  4. Validate your input! Identify the "entry-points" to your application. They can everything from webservices, REST-services, remote EJB classes, controllers, etc. For each method in these entry-points, ask yourself: "Will this method execute correctly if this parameter is null?" If the answer is no, add Validate.notNull(someParam, "Can't function when someParam is null!");. This will throw an IllegalArgumentException if the required parameter is missing. The good thing about this type of validation in the entry-points, is that you can then easily assume in the code being executed from the entry-point, that this variable will never be null! Also, if this fails, being at the entry-point, debugging is made a lot easier than it would if you just got a NullPointerException deep down in your code, since a failure like this can only mean one thing: The client didn't send you all the required information. In most cases you want to validate all input parameters, if you find yourself in a position where you need to allow a lot of null-values, it might be a sign of a badly designed interface, which needs refactoring/additions to suite the needs of the clients.

  5. When working with Collections, return an empty one rather than null!

  6. When working with a database, utilize not null-constraints. In that way, you'll know that a value read from the database cannot be null, and you won't have to check for it.

  7. Structure your code and stick with it. Doing this allows you to make assumptions about the behaviour of the code, for instance if all input to your application is validated, then you can assume that these values will never be null.

  8. If you are not already doing it, write automated tests of your code. By writing tests, you will reason about your code, and you will also become more confident that it does what it's supposed to. Also, automated tests guards you from blunders during refactoring, by letting you know immediatly that this piece of code is not doing what it used to.

You still have to null-check of course, but it can trimmed down to the bare minimum (i.e. the situation where know you might be getting a null-value, instead of everywhere just to be sure.) When it comes to null-checks, i actually prefer to use the ternary operator (but use with care, when you start nesting them they come really messy.)

public String nullSafeToString(final Object o) {
    return o != null ? o.toString() : "null";
}

Null object pattern can be used as a solution for this problem. For that, the class of the someObject should be modified.

public abstract class SomeObject {
   public abstract boolean isNil();
}

public class NullObject extends SomeObject {
   @Override
   public boolean isNil() {
      return true;
   }
}
public class RealObject extends SomeObject {
   @Override
   public boolean isNil() {
      return false;
   }
}

Now istead of checking,

 if (someobject != null) {
    someobject.doCalc();
}

We can use,

if (!someObject.isNil()) {
   someobject.doCalc();
}

Reference : https://www.tutorialspoint.com/design_pattern/null_object_pattern.htm


If you use (or planning to use) a Java IDE like JetBrains IntelliJ IDEA, Eclipse or Netbeans or a tool like findbugs then you can use annotations to solve this problem.

Basically, you've got @Nullable and @NotNull.

You can use in method and parameters, like this:

@NotNull public static String helloWorld() {
    return "Hello World";
}

or

@Nullable public static String helloWorld() {
    return "Hello World";
}

The second example won't compile (in IntelliJ IDEA).

When you use the first helloWorld() function in another piece of code:

public static void main(String[] args)
{
    String result = helloWorld();
    if(result != null) {
        System.out.println(result);
    }
}

Now the IntelliJ IDEA compiler will tell you that the check is useless, since the helloWorld() function won't return null, ever.

Using parameter

void someMethod(@NotNull someParameter) { }

if you write something like:

someMethod(null);

This won't compile.

Last example using @Nullable

@Nullable iWantToDestroyEverything() { return null; }

Doing this

iWantToDestroyEverything().something();

And you can be sure that this won't happen. :)

It's a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it's not supported by all the compilers.

In IntelliJ IDEA 10.5 and on, they added support for any other @Nullable @NotNull implementations.

See blog post More flexible and configurable @Nullable/@NotNull annotations.


In addition to using assert you can use the following:

if (someobject == null) {
    // Handle null here then move on.
}

This is slightly better than:

if (someobject != null) {
    .....
    .....



    .....
}

Functional approach may help to wrap the repetitive null checks and execute anonymous code like the below sample.

    BiConsumer<Object, Consumer<Object>> consumeIfPresent  = (s,f) ->{
        if(s!=null) {
            f.accept(s);
        }
    };

    consumeIfPresent.accept(null, (s)-> System.out.println(s) );
    consumeIfPresent.accept("test", (s)-> System.out.println(s));

    BiFunction<Object, Function<Object,Object>,Object> executeIfPresent  = (a,b) ->{
        if(a!=null) {
            return b.apply(a);
        }
        return null;
    };
    executeIfPresent.apply(null, (s)-> {System.out.println(s);return s;} );
    executeIfPresent.apply("test", (s)-> {System.out.println(s);return s;} );

Wherever you pass an array or a Vector, initialise these to empty ones, instead of null. - This way you can avoid lots of checking for null and all is good :)

public class NonNullThing {

   Vector vectorField = new Vector();

   int[] arrayField = new int[0];

   public NonNullThing() {

      // etc

   }

}

You can make one generic Method for object and string so that you can use it through out in your application- This could help you and your colleagues : Create a class eg. StringUtilities and add the method eg. getNullString

public static String getNullString(Object someobject)
{
   if(null==someobject )
        return null;

   else if(someobject.getClass().isInstance("") && 
          (((String)someobject).trim().equalsIgnoreCase("null")|| 
          ((String)someobject).trim().equalsIgnoreCase("")))
        return null;

   else if(someobject.getClass().isInstance(""))
        return (String)someobject;

   else
        return someobject.toString().trim();
}

And simply call this method as,

if (StringUtilities.getNullString(someobject) != null)
{ 
  //Do something
}

Rather than Null Object Pattern -- which has its uses -- you might consider situations where the null object is a bug.

When the exception is thrown, examine the stack trace and work through the bug.


I prefer this

public void simpleFunc(SomeObject someObject){
    someObject = someObject != null ? someObject : new SomeObject(null);
    someObject.doSomething();
}

Of course in my example SomeObject handles gracefully a null parameter. For example logging such event and doing nothing more.


If null-values are not allowed

If your method is called externally, start with something like this:

public void method(Object object) {
  if (object == null) {
    throw new IllegalArgumentException("...");
  }

Then, in the rest of that method, you'll know that object is not null.

If it is an internal method (not part of an API), just document that it cannot be null, and that's it.

Example:

public String getFirst3Chars(String text) {
  return text.subString(0, 3);
}

However, if your method just passes the value on, and the next method passes it on etc. it could get problematic. In that case you may want to check the argument as above.

If null is allowed

This really depends. If find that I often do something like this:

if (object == null) {
  // something
} else {
  // something else
}

So I branch, and do two completely different things. There is no ugly code snippet, because I really need to do two different things depending on the data. For example, should I work on the input, or should I calculate a good default value?


It's actually rare for me to use the idiom "if (object != null && ...".

It may be easier to give you examples, if you show examples of where you typically use the idiom.


  • If you consider an object should not be null (or it is a bug) use an assert.
  • If your method doesn't accept null params say it in the javadoc and use an assert.

You have to check for object != null only if you want to handle the case where the object may be null...

There is a proposal to add new annotations in Java7 to help with null / notnull params: http://tech.puredanger.com/java7/#jsr308


I find Guava Preconditions to be very useful in this case. I don't like leaving nulls to null pointer exception since the only way to understand an NPE is by locating the line number. Line numbers in production version and development version can be different.

Using Guava Preconditions, I can check null parameters and define a meaningful exception message in one line.

For example,

Preconditions.checkNotNull(paramVal, "Method foo received null paramVal");

Asking that question points out that you may be interested in error handling strategies. How and where to handle errors is a pervasive architectural question. There are several ways to do this.

My favorite: allow the Exceptions to ripple through - catch them at the 'main loop' or in some other function with the appropriate responsibilities. Checking for error conditions and handling them appropriately can be seen as a specialized responsibility.

Sure do have a look at Aspect Oriented Programming, too - they have neat ways to insert if( o == null ) handleNull() into your bytecode.


Sometimes, you have methods that operate on its parameters that define a symmetric operation:

a.f(b); <-> b.f(a);

If you know b can never be null, you can just swap it. It is most useful for equals: Instead of foo.equals("bar"); better do "bar".equals(foo);.


  • If you consider an object should not be null (or it is a bug) use an assert.
  • If your method doesn't accept null params say it in the javadoc and use an assert.

You have to check for object != null only if you want to handle the case where the object may be null...

There is a proposal to add new annotations in Java7 to help with null / notnull params: http://tech.puredanger.com/java7/#jsr308


You can also use the Checker Framework (with JDK 7 and beyond) to statically check for null values. This might solve a lot of problems, but requires running an extra tool that currently only works with OpenJDK AFAIK. https://checkerframework.org/


With Java 8, you could pass a supplier to a helper method like below,

if(CommonUtil.resolve(()-> a.b().c()).isPresent()) {

}

Above replaces boiler plate code like below,

if(a!=null && a.b()!=null && a.b().c()!=null) {

}

//CommonUtil.java

 public static <T> Optional<T> resolve(Supplier<T> resolver) {
        try {
            T result = resolver.get();
            return Optional.ofNullable(result);
        } catch (NullPointerException var2) {
            return Optional.empty();
        }
    }

We have been using Apache libraries (Apache Commons) for this issue.

ObjectUtils.equals(object, null)

or

CollectionUtils.isEmpty(myCollection);

or

StringUtils.isEmpty("string");

I like the previous answer before, as a practice, of providing initial default values or empty sets for collections to minimize the need.

These can be simple uses that keep you from having NullPointerException or using an empty collection. This doesnt answer the question for what to do with the null object, but these provide some checks for basic validations of the object or collection.

Hope this helps.


  1. Never initialise variables to null.
  2. If (1) is not possible, initialise all collections and arrays to empty collections/arrays.

Doing this in your own code and you can avoid != null checks.

Most of the time null checks seem to guard loops over collections or arrays, so just initialise them empty, you won't need any null checks.

// Bad
ArrayList<String> lemmings;
String[] names;

void checkLemmings() {
    if (lemmings != null) for(lemming: lemmings) {
        // do something
    }
}



// Good
ArrayList<String> lemmings = new ArrayList<String>();
String[] names = {};

void checkLemmings() {
    for(lemming: lemmings) {
        // do something
    }
}

There is a tiny overhead in this, but it's worth it for cleaner code and less NullPointerExceptions.


Another alternative to the != null check is (if you can't get rid of it design-wise):

Optional.ofNullable(someobject).ifPresent(someobject -> someobject.doCalc());

or

Optional.ofNullable(someobject).ifPresent(SomeClass::doCalc);

With SomeClass being someobject's type.

You can't get a return value back from doCalc() though, so only useful for void methods.


First of all, we can't really remove all null conditions. We can reduce them using @NotNull and @Nullable annotations (as mentioned already). But this needs to be backed by some framework. This is where OVal can help.

The basic idea is object/parameters/constructor should always satisfy preconditions. You can have a whole lot of preconditions such as Nullable, NotNull and OVal would take care that an object should be in a consistent state when invoked.

I guess OVal internally uses AspectJ to validate the preconditions.

@Guarded
public class BusinessObject
{
  public BusinessObject(@NotNull String name)
  {
    this.name = name;
  }

  ...
}

For example,

// Throws a ConstraintsViolatedException because parameter name is null
BusinessObject bo = new BusinessObject(null);

Asking that question points out that you may be interested in error handling strategies. How and where to handle errors is a pervasive architectural question. There are several ways to do this.

My favorite: allow the Exceptions to ripple through - catch them at the 'main loop' or in some other function with the appropriate responsibilities. Checking for error conditions and handling them appropriately can be seen as a specialized responsibility.

Sure do have a look at Aspect Oriented Programming, too - they have neat ways to insert if( o == null ) handleNull() into your bytecode.


Java 8 now has Optional class that wraps the object in consideration and if a value is present, isPresent() will return true and get() will return the value.

http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html


It is possible to define util methods which handles nested null-checks in an almost pretty way with Java 8 lambdas.

void example() {
    Entry entry = new Entry();
    // This is the same as H-MANs solution 
    Person person = getNullsafe(entry, e -> e.getPerson());    
    // Get object in several steps
    String givenName = getNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.getGivenName());
    // Call void methods
    doNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.nameIt());        
}

/** Return result of call to f1 with o1 if it is non-null, otherwise return null. */
public static <R, T1> R getNullsafe(T1 o1, Function<T1, R> f1) {
    if (o1 != null) return f1.apply(o1);
    return null; 
}

public static <R, T0, T1> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, R> f2) {
    return getNullsafe(getNullsafe(o0, f1), f2);
}

public static <R, T0, T1, T2> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Function<T2, R> f3) {
    return getNullsafe(getNullsafe(o0, f1, f2), f3);
}


/** Call consumer f1 with o1 if it is non-null, otherwise do nothing. */
public static <T1> void doNullsafe(T1 o1, Consumer<T1> f1) {
    if (o1 != null) f1.accept(o1);
}

public static <T0, T1> void doNullsafe(T0 o0, Function<T0, T1> f1, Consumer<T1> f2) {
    doNullsafe(getNullsafe(o0, f1), f2);
}

public static <T0, T1, T2> void doNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Consumer<T2> f3) {
    doNullsafe(getNullsafe(o0, f1, f2), f3);
}


class Entry {
    Person getPerson() { return null; }
}

class Person {
    Name getName() { return null; }
}

class Name {
    void nameIt() {}
    String getGivenName() { return null; }
}

(This answer was first posted here.)


The best way to avoid Null Checks in Java, is to properly handle and use exceptions. Null Checks in my experience have become more common and required as you move closer to the front-end, because it's closer to the user who may supply invalid information through the UI (such as, no value, being submitted for a field).

One may argue that you should be able to control what the UI is doing, lest you forget most UI is done through a third party library of some kind, which for example, may return either NULL or an Empty String for a blank text box, depending on the situation or the library.

You can combine the two like this:

try
{
  myvar = get_user_supplied_value(); 
  if (!myvar || myvar.length() == 0) { alert_the_user_somehow(); return; };

  process_user_input(myvar);
} catch (Exception ex) {
  handle_exception(ex);
}

Another approach people take is to say:

if (myvar && myvar.length() > 0)  { };

You could also throw an exception (which is what I prefer)

if (!myvar || myvar.length() == 0) {
 throw new Exception("You must supply a name!");
};

But that's up to you.


You can couple your Class with Unit Testing using a framework like JUnit. This way your code will be clean (no useless checkings) and you will be sure your instances wont be null.

This is one good reason (of many) to use Unit Testing.


Sometimes, you have methods that operate on its parameters that define a symmetric operation:

a.f(b); <-> b.f(a);

If you know b can never be null, you can just swap it. It is most useful for equals: Instead of foo.equals("bar"); better do "bar".equals(foo);.


May I answer it more generally!

We usually face this issue when the methods get the parameters in the way we not expected (bad method call is programmer's fault). For example: you expect to get an object, instead you get a null. You expect to get an String with at least one character, instead you get an empty String ...

So there is no difference between:

if(object == null){
   //you called my method badly!

}

or

if(str.length() == 0){
   //you called my method badly again!
}

They both want to make sure that we received valid parameters, before we do any other functions.

As mentioned in some other answers, to avoid above problems you can follow the Design by contract pattern. Please see http://en.wikipedia.org/wiki/Design_by_contract.

To implement this pattern in java, you can use core java annotations like javax.annotation.NotNull or use more sophisticated libraries like Hibernate Validator.

Just a sample:

getCustomerAccounts(@NotEmpty String customerId,@Size(min = 1) String accountType)

Now you can safely develop the core function of your method without needing to check input parameters, they guard your methods from unexpected parameters.

You can go a step further and make sure that only valid pojos could be created in your application. (sample from hibernate validator site)

public class Car {

   @NotNull
   private String manufacturer;

   @NotNull
   @Size(min = 2, max = 14)
   private String licensePlate;

   @Min(2)
   private int seatCount;

   // ...
}

I've tried the NullObjectPattern but for me is not always the best way to go. There are sometimes when a "no action" is not appropiate.

NullPointerException is a Runtime exception that means it's developers fault and with enough experience it tells you exactly where is the error.

Now to the answer:

Try to make all your attributes and its accessors as private as possible or avoid to expose them to the clients at all. You can have the argument values in the constructor of course, but by reducing the scope you don't let the client class pass an invalid value. If you need to modify the values, you can always create a new object. You check the values in the constructor only once and in the rest of the methods you can be almost sure that the values are not null.

Of course, experience is the better way to understand and apply this suggestion.

Byte!


Wherever you pass an array or a Vector, initialise these to empty ones, instead of null. - This way you can avoid lots of checking for null and all is good :)

public class NonNullThing {

   Vector vectorField = new Vector();

   int[] arrayField = new int[0];

   public NonNullThing() {

      // etc

   }

}

You can couple your Class with Unit Testing using a framework like JUnit. This way your code will be clean (no useless checkings) and you will be sure your instances wont be null.

This is one good reason (of many) to use Unit Testing.


If undefined values are not permitted:

You might configure your IDE to warn you about potential null dereferencing. E.g. in Eclipse, see Preferences > Java > Compiler > Errors/Warnings/Null analysis.

If undefined values are permitted:

If you want to define a new API where undefined values make sense, use the Option Pattern (may be familiar from functional languages). It has the following advantages:

  • It is stated explicitly in the API whether an input or output exists or not.
  • The compiler forces you to handle the "undefined" case.
  • Option is a monad, so there is no need for verbose null checking, just use map/foreach/getOrElse or a similar combinator to safely use the value (example).

Java 8 has a built-in Optional class (recommended); for earlier versions, there are library alternatives, for example Guava's Optional or FunctionalJava's Option. But like many functional-style patterns, using Option in Java (even 8) results in quite some boilerplate, which you can reduce using a less verbose JVM language, e.g. Scala or Xtend.

If you have to deal with an API which might return nulls, you can't do much in Java. Xtend and Groovy have the Elvis operator ?: and the null-safe dereference operator ?., but note that this returns null in case of a null reference, so it just "defers" the proper handling of null.


Only for this situation -

Not checking if a variable is null before invoking an equals method (a string compare example below):

if ( foo.equals("bar") ) {
 // ...
}

will result in a NullPointerException if foo doesn't exist.

You can avoid that if you compare your Strings like this:

if ( "bar".equals(foo) ) {
 // ...
}

One more alternative:

The following simple function helps to hide the null-check (I don't know why, but I haven't found it as part of the same common library):

public static <T> boolean isNull(T argument) {
    return (argument == null);
}

You could now write

if (!isNull(someobject)) {
    someobject.doCalc();
}

which is IMO a better way of expressing != null.


You can use an interceptor before the method call. That is what aspect-oriented programming focus on.

Suppose M1(Object test) is a method and M2 is a method where we apply an aspect before a method call, M2(Object test2). If test2 != null then call M1, otherwise do another thing. It works for all methods with whom you want to apply an aspect for. If you want to apply an aspect for an instance field and constructor you can use AspectJ. Spring can also be the best choice for a method aspect.


Here is my approach ..

class MyObjectHandler
{
public static final int EXCEPTION = (-3);
public static final int INACCESSIBLE = (-2);

public static int doSomething (MyObject obj, MyObjectParameter [] input)
{
    int returnValue= 0;

    try
    {
        if (obj != null)
        {
            returnValue = obj.doSomething(input);
        }
        else
        {
            returnValue = MyObjectHandler.INACCESSIBLE;
        }
    }
    catch (Exception e)
    {
        e.printStack();
        returnValue = MyObjectHandler.EXCEPTION;
    }
    finally
    {
        return returnValue;
    }
}

..

}

Then your code will be just like:

import xx.xx.xx.MyObjectHandler;
import xx.xx.xx.MyObjectParameter;

class Test
{

    public static void main ()
    {

        MyObject obj = null;

        MyObjectHandler.doSomething(obj, null);

    }

    ..

}

Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException. It avoids any runtime NullPointerExceptions and supports us in developing clean and neat Java APIs or Applications. Like Collections and arrays, it is also a Container to hold at most one value.

Below are some useful link you can follow

https://www.mkyong.com/java8/java-8-optional-in-depth/

https://dzone.com/articles/java-8-optional-avoid-null-and


If you are using java8 or later go for the isNull(yourObject) from java.util.Objects.

Example:-

String myObject = null;

Objects.isNull(myObject); //will return true

Usage: The below code returns a non null value (if the name is not null then that value will be returned else the default value will be returned).

final String name = "Jobin";
String nonNullValue = Optional.ofNullable(name).filter(Objects::nonNull).orElse("DefaultName");

Rather than Null Object Pattern -- which has its uses -- you might consider situations where the null object is a bug.

When the exception is thrown, examine the stack trace and work through the bug.


  1. Never initialise variables to null.
  2. If (1) is not possible, initialise all collections and arrays to empty collections/arrays.

Doing this in your own code and you can avoid != null checks.

Most of the time null checks seem to guard loops over collections or arrays, so just initialise them empty, you won't need any null checks.

// Bad
ArrayList<String> lemmings;
String[] names;

void checkLemmings() {
    if (lemmings != null) for(lemming: lemmings) {
        // do something
    }
}



// Good
ArrayList<String> lemmings = new ArrayList<String>();
String[] names = {};

void checkLemmings() {
    for(lemming: lemmings) {
        // do something
    }
}

There is a tiny overhead in this, but it's worth it for cleaner code and less NullPointerExceptions.


You can use FindBugs. They also have an Eclipse plugin) that helps you find duplicate null checks (among other things), but keep in mind that sometimes you should opt for defensive programming. There is also Contracts for Java which may be helpful.


Wow, I almost hate to add another answer when we have 57 different ways to recommend the NullObject pattern, but I think that some people interested in this question may like to know that there is a proposal on the table for Java 7 to add "null-safe handling"—a streamlined syntax for if-not-equal-null logic.

The example given by Alex Miller looks like this:

public String getPostcode(Person person) {  
  return person?.getAddress()?.getPostcode();  
}  

The ?. means only de-reference the left identifier if it is not null, otherwise evaluate the remainder of the expression as null. Some people, like Java Posse member Dick Wall and the voters at Devoxx really love this proposal, but there is opposition too, on the grounds that it will actually encourage more use of null as a sentinel value.


Update: An official proposal for a null-safe operator in Java 7 has been submitted under Project Coin. The syntax is a little different than the example above, but it's the same notion.


Update: The null-safe operator proposal didn't make it into Project Coin. So, you won't be seeing this syntax in Java 7.


You can make one generic Method for object and string so that you can use it through out in your application- This could help you and your colleagues : Create a class eg. StringUtilities and add the method eg. getNullString

public static String getNullString(Object someobject)
{
   if(null==someobject )
        return null;

   else if(someobject.getClass().isInstance("") && 
          (((String)someobject).trim().equalsIgnoreCase("null")|| 
          ((String)someobject).trim().equalsIgnoreCase("")))
        return null;

   else if(someobject.getClass().isInstance(""))
        return (String)someobject;

   else
        return someobject.toString().trim();
}

And simply call this method as,

if (StringUtilities.getNullString(someobject) != null)
{ 
  //Do something
}

The Google collections framework offers a good and elegant way to achieve the null check.

There is a method in a library class like this:

static <T> T checkNotNull(T e) {
   if (e == null) {
      throw new NullPointerException();
   }
   return e;
}

And the usage is (with import static):

...
void foo(int a, Person p) {
   if (checkNotNull(p).getAge() > a) {
      ...
   }
   else {
      ...
   }
}
...

Or in your example:

checkNotNull(someobject).doCalc();

Wow, I almost hate to add another answer when we have 57 different ways to recommend the NullObject pattern, but I think that some people interested in this question may like to know that there is a proposal on the table for Java 7 to add "null-safe handling"—a streamlined syntax for if-not-equal-null logic.

The example given by Alex Miller looks like this:

public String getPostcode(Person person) {  
  return person?.getAddress()?.getPostcode();  
}  

The ?. means only de-reference the left identifier if it is not null, otherwise evaluate the remainder of the expression as null. Some people, like Java Posse member Dick Wall and the voters at Devoxx really love this proposal, but there is opposition too, on the grounds that it will actually encourage more use of null as a sentinel value.


Update: An official proposal for a null-safe operator in Java 7 has been submitted under Project Coin. The syntax is a little different than the example above, but it's the same notion.


Update: The null-safe operator proposal didn't make it into Project Coin. So, you won't be seeing this syntax in Java 7.


Java 7 has a new java.util.Objects utility class on which there is a requireNonNull() method. All this does is throw a NullPointerException if its argument is null, but it cleans up the code a bit. Example:

Objects.requireNonNull(someObject);
someObject.doCalc();

The method is most useful for checking just before an assignment in a constructor, where each use of it can save three lines of code:

Parent(Child child) {
   if (child == null) {
      throw new NullPointerException("child");
   }
   this.child = child;
}

becomes

Parent(Child child) {
   this.child = Objects.requireNonNull(child, "child");
}

This is a very common problem for every Java developer. So there is official support in Java 8 to address these issues without cluttered code.

Java 8 has introduced java.util.Optional<T>. It is a container that may or may not hold a non-null value. Java 8 has given a safer way to handle an object whose value may be null in some of the cases. It is inspired from the ideas of Haskell and Scala.

In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional<T> class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.

In above example we have a home service factory that returns a handle to multiple appliances available in the home. But these services may or may not be available/functional; it means it may result in a NullPointerException. Instead of adding a null if condition before using any service, let's wrap it in to Optional<Service>.

WRAPPING TO OPTION<T>

Let's consider a method to get a reference of a service from a factory. Instead of returning the service reference, wrap it with Optional. It lets the API user know that the returned service may or may not available/functional, use defensively

public Optional<Service> getRefrigertorControl() {
      Service s = new  RefrigeratorService();
       //...
      return Optional.ofNullable(s);
   }

As you see Optional.ofNullable() provides an easy way to get the reference wrapped. There are another ways to get the reference of Optional, either Optional.empty() & Optional.of(). One for returning an empty object instead of retuning null and the other to wrap a non-nullable object, respectively.

SO HOW EXACTLY IT HELPS TO AVOID A NULL CHECK?

Once you have wrapped a reference object, Optional provides many useful methods to invoke methods on a wrapped reference without NPE.

Optional ref = homeServices.getRefrigertorControl();
ref.ifPresent(HomeServices::switchItOn);

Optional.ifPresent invokes the given Consumer with a reference if it is a non-null value. Otherwise, it does nothing.

@FunctionalInterface
public interface Consumer<T>

Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects. It is so clean and easy to understand. In the above code example, HomeService.switchOn(Service) gets invoked if the Optional holding reference is non-null.

We use the ternary operator very often for checking null condition and return an alternative value or default value. Optional provides another way to handle the same condition without checking null. Optional.orElse(defaultObj) returns defaultObj if the Optional has a null value. Let's use this in our sample code:

public static Optional<HomeServices> get() {
    service = Optional.of(service.orElse(new HomeServices()));
    return service;
}

Now HomeServices.get() does same thing, but in a better way. It checks whether the service is already initialized of not. If it is then return the same or create a new New service. Optional<T>.orElse(T) helps to return a default value.

Finally, here is our NPE as well as null check-free code:

import java.util.Optional;
public class HomeServices {
    private static final int NOW = 0;
    private static Optional<HomeServices> service;

public static Optional<HomeServices> get() {
    service = Optional.of(service.orElse(new HomeServices()));
    return service;
}

public Optional<Service> getRefrigertorControl() {
    Service s = new  RefrigeratorService();
    //...
    return Optional.ofNullable(s);
}

public static void main(String[] args) {
    /* Get Home Services handle */
    Optional<HomeServices> homeServices = HomeServices.get();
    if(homeServices != null) {
        Optional<Service> refrigertorControl = homeServices.get().getRefrigertorControl();
        refrigertorControl.ifPresent(HomeServices::switchItOn);
    }
}

public static void switchItOn(Service s){
         //...
    }
}

The complete post is NPE as well as Null check-free code … Really?.


  • If you consider an object should not be null (or it is a bug) use an assert.
  • If your method doesn't accept null params say it in the javadoc and use an assert.

You have to check for object != null only if you want to handle the case where the object may be null...

There is a proposal to add new annotations in Java7 to help with null / notnull params: http://tech.puredanger.com/java7/#jsr308


Kotlin with null safety is elegant alternative, but it means a larger change.


Only for this situation -

Not checking if a variable is null before invoking an equals method (a string compare example below):

if ( foo.equals("bar") ) {
 // ...
}

will result in a NullPointerException if foo doesn't exist.

You can avoid that if you compare your Strings like this:

if ( "bar".equals(foo) ) {
 // ...
}

Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections

Example:

String foo;
...
if( StringUtils.isBlank( foo ) ) {
   ///do something
}

or (depending on what you need to check):

String foo;
...
if( StringUtils.isEmpty( foo ) ) {
   ///do something
}

The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.

Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)

public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
    Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
    return read(new StringReader(xml), true, validationEventHandler);
}

And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar)

Example on how to use this static classf from spring(org.springframework.util.Assert)

Assert.notNull(validationEventHandler,"ValidationHandler not Injected");

Null is not a 'problem'. It is an integral part of a complete modeling tool set. Software aims to model the complexity of the world and null bears its burden. Null indicates 'No data' or 'Unknown' in Java and the like. So it is appropriate to use nulls for these purposes. I don't prefer the 'Null object' pattern; I think it rise the 'who will guard the guardians' problem.
If you ask me what is the name of my girlfriend I'll tell you that I have no girlfriend. In the Java language I'll return null. An alternative would be to throw meaningful exception to indicate some problem that can't be (or don't want to be) solved right there and delegate it somewhere higher in the stack to retry or report data access error to the user.

  1. For an 'unknown question' give 'unknown answer'. (Be null-safe where this is correct from business point of view) Checking arguments for null once inside a method before usage relieves multiple callers from checking them before a call.

    public Photo getPhotoOfThePerson(Person person) {
        if (person == null)
            return null;
        // Grabbing some resources or intensive calculation
        // using person object anyhow.
    }
    

    Previous leads to normal logic flow to get no photo of a non-existent girlfriend from my photo library.

    getPhotoOfThePerson(me.getGirlfriend())
    

    And it fits with new coming Java API (looking forward)

    getPhotoByName(me.getGirlfriend()?.getName())
    

    While it is rather 'normal business flow' not to find photo stored into the DB for some person, I used to use pairs like below for some other cases

    public static MyEnum parseMyEnum(String value); // throws IllegalArgumentException
    public static MyEnum parseMyEnumOrNull(String value);
    

    And don't loathe to type <alt> + <shift> + <j> (generate javadoc in Eclipse) and write three additional words for you public API. This will be more than enough for all but those who don't read documentation.

    /**
     * @return photo or null
     */
    

    or

    /**
     * @return photo, never null
     */
    
  2. This is rather theoretical case and in most cases you should prefer java null safe API (in case it will be released in another 10 years), but NullPointerException is subclass of an Exception. Thus it is a form of Throwable that indicates conditions that a reasonable application might want to catch (javadoc)! To use the first most advantage of exceptions and separate error-handling code from 'regular' code (according to creators of Java) it is appropriate, as for me, to catch NullPointerException.

    public Photo getGirlfriendPhoto() {
        try {
            return appContext.getPhotoDataSource().getPhotoByName(me.getGirlfriend().getName());
        } catch (NullPointerException e) {
            return null;
        }
    }
    

    Questions could arise:

    Q. What if getPhotoDataSource() returns null?
    A. It is up to business logic. If I fail to find a photo album I'll show you no photos. What if appContext is not initialized? This method's business logic puts up with this. If the same logic should be more strict then throwing an exception it is part of the business logic and explicit check for null should be used (case 3). The new Java Null-safe API fits better here to specify selectively what implies and what does not imply to be initialized to be fail-fast in case of programmer errors.

    Q. Redundant code could be executed and unnecessary resources could be grabbed.
    A. It could take place if getPhotoByName() would try to open a database connection, create PreparedStatement and use the person name as an SQL parameter at last. The approach for an unknown question gives an unknown answer (case 1) works here. Before grabbing resources the method should check parameters and return 'unknown' result if needed.

    Q. This approach has a performance penalty due to the try closure opening.
    A. Software should be easy to understand and modify firstly. Only after this, one could think about performance, and only if needed! and where needed! (source), and many others).

    PS. This approach will be as reasonable to use as the separate error-handling code from "regular" code principle is reasonable to use in some place. Consider the next example:

    public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {
        try {
            Result1 result1 = performSomeCalculation(predicate);
            Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());
            Result3 result3 = performThirdCalculation(result2.getSomeProperty());
            Result4 result4 = performLastCalculation(result3.getSomeProperty());
            return result4.getSomeProperty();
        } catch (NullPointerException e) {
            return null;
        }
    }
    
    public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {
        SomeValue result = null;
        if (predicate != null) {
            Result1 result1 = performSomeCalculation(predicate);
            if (result1 != null && result1.getSomeProperty() != null) {
                Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());
                if (result2 != null && result2.getSomeProperty() != null) {
                    Result3 result3 = performThirdCalculation(result2.getSomeProperty());
                    if (result3 != null && result3.getSomeProperty() != null) {
                        Result4 result4 = performLastCalculation(result3.getSomeProperty());
                        if (result4 != null) {
                            result = result4.getSomeProperty();
                        }
                    }
                }
            }
        }
        return result;
    }
    

    PPS. For those fast to downvote (and not so fast to read documentation) I would like to say that I've never caught a null-pointer exception (NPE) in my life. But this possibility was intentionally designed by the Java creators because NPE is a subclass of Exception. We have a precedent in Java history when ThreadDeath is an Error not because it is actually an application error, but solely because it was not intended to be caught! How much NPE fits to be an Error than ThreadDeath! But it is not.

  3. Check for 'No data' only if business logic implies it.

    public void updatePersonPhoneNumber(Long personId, String phoneNumber) {
        if (personId == null)
            return;
        DataSource dataSource = appContext.getStuffDataSource();
        Person person = dataSource.getPersonById(personId);
        if (person != null) {
            person.setPhoneNumber(phoneNumber);
            dataSource.updatePerson(person);
        } else {
            Person = new Person(personId);
            person.setPhoneNumber(phoneNumber);
            dataSource.insertPerson(person);
        }
    }
    

    and

    public void updatePersonPhoneNumber(Long personId, String phoneNumber) {
        if (personId == null)
            return;
        DataSource dataSource = appContext.getStuffDataSource();
        Person person = dataSource.getPersonById(personId);
        if (person == null)
            throw new SomeReasonableUserException("What are you thinking about ???");
        person.setPhoneNumber(phoneNumber);
        dataSource.updatePerson(person);
    }
    

    If appContext or dataSource is not initialized unhandled runtime NullPointerException will kill current thread and will be processed by Thread.defaultUncaughtExceptionHandler (for you to define and use your favorite logger or other notification mechanizm). If not set, ThreadGroup#uncaughtException will print stacktrace to system err. One should monitor application error log and open Jira issue for each unhandled exception which in fact is application error. Programmer should fix bug somewhere in initialization stuff.


I'm a fan of "fail fast" code. Ask yourself - are you doing something useful in the case where the parameter is null? If you don't have a clear answer for what your code should do in that case... I.e. it should never be null in the first place, then ignore it and allow a NullPointerException to be thrown. The calling code will make just as much sense of an NPE as it would an IllegalArgumentException, but it'll be easier for the developer to debug and understand what went wrong if an NPE is thrown rather than your code attempting to execute some other unexpected contingency logic - which ultimately results in the application failing anyway.


This is a very common problem for every Java developer. So there is official support in Java 8 to address these issues without cluttered code.

Java 8 has introduced java.util.Optional<T>. It is a container that may or may not hold a non-null value. Java 8 has given a safer way to handle an object whose value may be null in some of the cases. It is inspired from the ideas of Haskell and Scala.

In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional<T> class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.

In above example we have a home service factory that returns a handle to multiple appliances available in the home. But these services may or may not be available/functional; it means it may result in a NullPointerException. Instead of adding a null if condition before using any service, let's wrap it in to Optional<Service>.

WRAPPING TO OPTION<T>

Let's consider a method to get a reference of a service from a factory. Instead of returning the service reference, wrap it with Optional. It lets the API user know that the returned service may or may not available/functional, use defensively

public Optional<Service> getRefrigertorControl() {
      Service s = new  RefrigeratorService();
       //...
      return Optional.ofNullable(s);
   }

As you see Optional.ofNullable() provides an easy way to get the reference wrapped. There are another ways to get the reference of Optional, either Optional.empty() & Optional.of(). One for returning an empty object instead of retuning null and the other to wrap a non-nullable object, respectively.

SO HOW EXACTLY IT HELPS TO AVOID A NULL CHECK?

Once you have wrapped a reference object, Optional provides many useful methods to invoke methods on a wrapped reference without NPE.

Optional ref = homeServices.getRefrigertorControl();
ref.ifPresent(HomeServices::switchItOn);

Optional.ifPresent invokes the given Consumer with a reference if it is a non-null value. Otherwise, it does nothing.

@FunctionalInterface
public interface Consumer<T>

Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects. It is so clean and easy to understand. In the above code example, HomeService.switchOn(Service) gets invoked if the Optional holding reference is non-null.

We use the ternary operator very often for checking null condition and return an alternative value or default value. Optional provides another way to handle the same condition without checking null. Optional.orElse(defaultObj) returns defaultObj if the Optional has a null value. Let's use this in our sample code:

public static Optional<HomeServices> get() {
    service = Optional.of(service.orElse(new HomeServices()));
    return service;
}

Now HomeServices.get() does same thing, but in a better way. It checks whether the service is already initialized of not. If it is then return the same or create a new New service. Optional<T>.orElse(T) helps to return a default value.

Finally, here is our NPE as well as null check-free code:

import java.util.Optional;
public class HomeServices {
    private static final int NOW = 0;
    private static Optional<HomeServices> service;

public static Optional<HomeServices> get() {
    service = Optional.of(service.orElse(new HomeServices()));
    return service;
}

public Optional<Service> getRefrigertorControl() {
    Service s = new  RefrigeratorService();
    //...
    return Optional.ofNullable(s);
}

public static void main(String[] args) {
    /* Get Home Services handle */
    Optional<HomeServices> homeServices = HomeServices.get();
    if(homeServices != null) {
        Optional<Service> refrigertorControl = homeServices.get().getRefrigertorControl();
        refrigertorControl.ifPresent(HomeServices::switchItOn);
    }
}

public static void switchItOn(Service s){
         //...
    }
}

The complete post is NPE as well as Null check-free code … Really?.


Wherever you pass an array or a Vector, initialise these to empty ones, instead of null. - This way you can avoid lots of checking for null and all is good :)

public class NonNullThing {

   Vector vectorField = new Vector();

   int[] arrayField = new int[0];

   public NonNullThing() {

      // etc

   }

}

Common "problem" in Java indeed.

First, my thoughts on this:

I consider that it is bad to "eat" something when NULL was passed where NULL isn't a valid value. If you're not exiting the method with some sort of error then it means nothing went wrong in your method which is not true. Then you probably return null in this case, and in the receiving method you again check for null, and it never ends, and you end up with "if != null", etc..

So, IMHO, null must be a critical error which prevents further execution (that is, where null is not a valid value).

The way I solve this problem is this:

First, I follow this convention:

  1. All public methods / API always check its arguments for null
  2. All private methods do not check for null since they are controlled methods (just let die with nullpointer exception in case it wasn't handled above)
  3. The only other methods which do not check for null are utility methods. They are public, but if you call them for some reason, you know what parameters you pass. This is like trying to boil water in the kettle without providing water...

And finally, in the code, the first line of the public method goes like this:

ValidationUtils.getNullValidator().addParam(plans, "plans").addParam(persons, "persons").validate();

Note that addParam() returns self, so that you can add more parameters to check.

Method validate() will throw checked ValidationException if any of the parameters is null (checked or unchecked is more a design/taste issue, but my ValidationException is checked).

void validate() throws ValidationException;

The message will contain the following text if, for example, "plans" is null:

"Illegal argument value null is encountered for parameter [plans]"

As you can see, the second value in the addParam() method (string) is needed for the user message, because you cannot easily detect passed-in variable name, even with reflection (not subject of this post anyway...).

And yes, we know that beyond this line we will no longer encounter a null value so we just safely invoke methods on those objects.

This way, the code is clean, easy maintainable and readable.


For utility classes, you can check that parameters are not null.

In all other cases, you may not have to. Use encapsulation as much as possible, thus reducing the places you feel tempted to check for null.


I highly disregard answers that suggest using the null objects in every situation. This pattern may break the contract and bury problems deeper and deeper instead of solving them, not mentioning that used inappropriately will create another pile of boilerplate code that will require future maintenance.

In reality if something returned from a method can be null and the calling code has to make decision upon that, there should an earlier call that ensures the state.

Also keep in mind, that null object pattern will be memory hungry if used without care. For this - the instance of a NullObject should be shared between owners, and not be an unigue instance for each of these.

Also I would not recommend using this pattern where the type is meant to be a primitive type representation - like mathematical entities, that are not scalars: vectors, matrices, complex numbers and POD(Plain Old Data) objects, which are meant to hold state in form of Java built-in types. In the latter case you would end up calling getter methods with arbitrary results. For example what should a NullPerson.getName() method return?

It's worth considering such cases in order to avoid absurd results.


Since Java 7 the class java.util.Objects exists.

But since Java 8, you can use Objects.isNull(var) and Objects.nonNull(var) methods of Objects class to do the null pointer check.

For example,

String var1 = null;
Date var2 = null;
Long var3 = null;

if(Objects.isNull(var1) && Objects.isNull(var2) && Objects.isNull(var3))
    System.out.println("All Null");
else if (Objects.nonNull(var1) && Objects.nonNull(var2) && Objects.nonNull(var3))
    System.out.println("All Not Null");

You can avoid most a lot to avoid NullPointerException by just following most of the others answers to the Question, I just want to add few more ways which have been introduced in Java 9 to handle this scenario gracefully and also showcase a few of the older ones can also be used and thus reducing your efforts.

  1. public static boolean isNull(Object obj)

    Returns true if the provided reference is null otherwise returns false.

    Since Java 1.8

  2. public static boolean nonNull(Object obj)

    Returns true if the provided reference is non-null otherwise returns false.

    Since Java 1.8

  3. public static <T> T requireNonNullElse?(T obj, T defaultObj)

    Returns the first argument if it is non-null and otherwise returns the non-null second argument.

    Since Java 9

  4. public static <T> T requireNonNullElseGet?(T obj, Supplier<? extends T> supplier)

    Returns the first argument if it is non-null and otherwise returns the non-null value of supplier.get().

    Since Java 9

  5. public static <T> T requireNonNull?(T obj, Supplier<String> messageSupplier)

    Checks that the specified object reference is not null and throws a customized NullPointerException otherwise.

    Since Java 1.8

Further details about the above functions can be found here.


If null-values are not allowed

If your method is called externally, start with something like this:

public void method(Object object) {
  if (object == null) {
    throw new IllegalArgumentException("...");
  }

Then, in the rest of that method, you'll know that object is not null.

If it is an internal method (not part of an API), just document that it cannot be null, and that's it.

Example:

public String getFirst3Chars(String text) {
  return text.subString(0, 3);
}

However, if your method just passes the value on, and the next method passes it on etc. it could get problematic. In that case you may want to check the argument as above.

If null is allowed

This really depends. If find that I often do something like this:

if (object == null) {
  // something
} else {
  // something else
}

So I branch, and do two completely different things. There is no ugly code snippet, because I really need to do two different things depending on the data. For example, should I work on the input, or should I calculate a good default value?


It's actually rare for me to use the idiom "if (object != null && ...".

It may be easier to give you examples, if you show examples of where you typically use the idiom.


Common "problem" in Java indeed.

First, my thoughts on this:

I consider that it is bad to "eat" something when NULL was passed where NULL isn't a valid value. If you're not exiting the method with some sort of error then it means nothing went wrong in your method which is not true. Then you probably return null in this case, and in the receiving method you again check for null, and it never ends, and you end up with "if != null", etc..

So, IMHO, null must be a critical error which prevents further execution (that is, where null is not a valid value).

The way I solve this problem is this:

First, I follow this convention:

  1. All public methods / API always check its arguments for null
  2. All private methods do not check for null since they are controlled methods (just let die with nullpointer exception in case it wasn't handled above)
  3. The only other methods which do not check for null are utility methods. They are public, but if you call them for some reason, you know what parameters you pass. This is like trying to boil water in the kettle without providing water...

And finally, in the code, the first line of the public method goes like this:

ValidationUtils.getNullValidator().addParam(plans, "plans").addParam(persons, "persons").validate();

Note that addParam() returns self, so that you can add more parameters to check.

Method validate() will throw checked ValidationException if any of the parameters is null (checked or unchecked is more a design/taste issue, but my ValidationException is checked).

void validate() throws ValidationException;

The message will contain the following text if, for example, "plans" is null:

"Illegal argument value null is encountered for parameter [plans]"

As you can see, the second value in the addParam() method (string) is needed for the user message, because you cannot easily detect passed-in variable name, even with reflection (not subject of this post anyway...).

And yes, we know that beyond this line we will no longer encounter a null value so we just safely invoke methods on those objects.

This way, the code is clean, easy maintainable and readable.


Just don't ever use null. Don't allow it.

In my classes, most fields and local variables have non-null default values, and I add contract statements (always-on asserts) everywhere in the code to make sure this is being enforced (since it's more succinct, and more expressive than letting it come up as an NPE and then having to resolve the line number, etc.).

Once I adopted this practice, I noticed that the problems seemed to fix themselves. You'd catch things much earlier in the development process just by accident and realize you had a weak spot.. and more importantly.. it helps encapsulate different modules' concerns, different modules can 'trust' each other, and no more littering the code with if = null else constructs!

This is defensive programming and results in much cleaner code in the long run. Always sanitize the data, e.g. here by enforcing rigid standards, and the problems go away.

class C {
    private final MyType mustBeSet;
    public C(MyType mything) {
       mustBeSet=Contract.notNull(mything);
    }
   private String name = "<unknown>";
   public void setName(String s) {
      name = Contract.notNull(s);
   }
}


class Contract {
    public static <T> T notNull(T t) { if (t == null) { throw new ContractException("argument must be non-null"); return t; }
}

The contracts are like mini-unit tests which are always running, even in production, and when things fail, you know why, rather than a random NPE you have to somehow figure out.


Probably the best alternative for Java 8 or newer is to use the Optional class.

Optional stringToUse = Optional.of("optional is there");
stringToUse.ifPresent(System.out::println);

This is especially handy for long chains of possible null values. Example:

Optional<Integer> i = Optional.ofNullable(wsObject.getFoo())
    .map(f -> f.getBar())
    .map(b -> b.getBaz())
    .map(b -> b.getInt());

Example on how to throw exception on null:

Optional optionalCarNull = Optional.ofNullable(someNull);
optionalCarNull.orElseThrow(IllegalStateException::new);

Java 7 introduced the Objects.requireNonNull method which can be handy when something should be checked for non-nullness. Example:

String lowerVal = Objects.requireNonNull(someVar, "input cannot be null or empty").toLowerCase();

I'm a fan of "fail fast" code. Ask yourself - are you doing something useful in the case where the parameter is null? If you don't have a clear answer for what your code should do in that case... I.e. it should never be null in the first place, then ignore it and allow a NullPointerException to be thrown. The calling code will make just as much sense of an NPE as it would an IllegalArgumentException, but it'll be easier for the developer to debug and understand what went wrong if an NPE is thrown rather than your code attempting to execute some other unexpected contingency logic - which ultimately results in the application failing anyway.


Java 8 now has Optional class that wraps the object in consideration and if a value is present, isPresent() will return true and get() will return the value.

http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html


public static <T> T ifNull(T toCheck, T ifNull) {
    if (toCheck == null) {
           return ifNull;
    }
    return toCheck;
}

You can also use the Checker Framework (with JDK 7 and beyond) to statically check for null values. This might solve a lot of problems, but requires running an extra tool that currently only works with OpenJDK AFAIK. https://checkerframework.org/


Sometimes, you have methods that operate on its parameters that define a symmetric operation:

a.f(b); <-> b.f(a);

If you know b can never be null, you can just swap it. It is most useful for equals: Instead of foo.equals("bar"); better do "bar".equals(foo);.


You can use an interceptor before the method call. That is what aspect-oriented programming focus on.

Suppose M1(Object test) is a method and M2 is a method where we apply an aspect before a method call, M2(Object test2). If test2 != null then call M1, otherwise do another thing. It works for all methods with whom you want to apply an aspect for. If you want to apply an aspect for an instance field and constructor you can use AspectJ. Spring can also be the best choice for a method aspect.


Ultimately, the only way to completely solve this problem is by using a different programming language:

  • In Objective-C, you can do the equivalent of invoking a method on nil, and absolutely nothing will happen. This makes most null checks unnecessary, but it can make errors much harder to diagnose.
  • In Nice, a Java-derived language, there are two versions of all types: a potentially-null version and a not-null version. You can only invoke methods on not-null types. Potentially-null types can be converted to not-null types through explicit checking for null. This makes it much easier to know where null checks are necessary and where they aren't.

Wow, I almost hate to add another answer when we have 57 different ways to recommend the NullObject pattern, but I think that some people interested in this question may like to know that there is a proposal on the table for Java 7 to add "null-safe handling"—a streamlined syntax for if-not-equal-null logic.

The example given by Alex Miller looks like this:

public String getPostcode(Person person) {  
  return person?.getAddress()?.getPostcode();  
}  

The ?. means only de-reference the left identifier if it is not null, otherwise evaluate the remainder of the expression as null. Some people, like Java Posse member Dick Wall and the voters at Devoxx really love this proposal, but there is opposition too, on the grounds that it will actually encourage more use of null as a sentinel value.


Update: An official proposal for a null-safe operator in Java 7 has been submitted under Project Coin. The syntax is a little different than the example above, but it's the same notion.


Update: The null-safe operator proposal didn't make it into Project Coin. So, you won't be seeing this syntax in Java 7.


Java 8 has introduced a new class Optional in java.util package.

Advantages of Java 8 Optional:

1.) Null checks are not required.
2.) No more NullPointerException at run-time.
3.) We can develop clean and neat APIs.

Optional - A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

For more details find here oracle docs :- https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html


If null-values are not allowed

If your method is called externally, start with something like this:

public void method(Object object) {
  if (object == null) {
    throw new IllegalArgumentException("...");
  }

Then, in the rest of that method, you'll know that object is not null.

If it is an internal method (not part of an API), just document that it cannot be null, and that's it.

Example:

public String getFirst3Chars(String text) {
  return text.subString(0, 3);
}

However, if your method just passes the value on, and the next method passes it on etc. it could get problematic. In that case you may want to check the argument as above.

If null is allowed

This really depends. If find that I often do something like this:

if (object == null) {
  // something
} else {
  // something else
}

So I branch, and do two completely different things. There is no ugly code snippet, because I really need to do two different things depending on the data. For example, should I work on the input, or should I calculate a good default value?


It's actually rare for me to use the idiom "if (object != null && ...".

It may be easier to give you examples, if you show examples of where you typically use the idiom.


Java 7 has a new java.util.Objects utility class on which there is a requireNonNull() method. All this does is throw a NullPointerException if its argument is null, but it cleans up the code a bit. Example:

Objects.requireNonNull(someObject);
someObject.doCalc();

The method is most useful for checking just before an assignment in a constructor, where each use of it can save three lines of code:

Parent(Child child) {
   if (child == null) {
      throw new NullPointerException("child");
   }
   this.child = child;
}

becomes

Parent(Child child) {
   this.child = Objects.requireNonNull(child, "child");
}

One Option you have

  • Use checker framework's @RequiresNonNull on methods. for ex you get this if you call a method annotated as such, with a null argument. It will fail during compile, even before your code runs! since at runtime it will be NullPointerException

    @RequiresNonNull(value = { "#1" })
    static void check( Boolean x) {
        if (x) System.out.println("true");
        else System.out.println("false");
    }
    
    public static void main(String[] args) {
    
    
        check(null);
    
    }
    

gets

[ERROR] found   : null
[ERROR] required: @Initialized @NonNull Boolean
[ERROR] -> [Help 1]

There are other methods like Use Java 8's Optional, Guava Annotations, Null Object pattern etc. Does not matter as long as you obtain your goal of avoiding !=null


The Google collections framework offers a good and elegant way to achieve the null check.

There is a method in a library class like this:

static <T> T checkNotNull(T e) {
   if (e == null) {
      throw new NullPointerException();
   }
   return e;
}

And the usage is (with import static):

...
void foo(int a, Person p) {
   if (checkNotNull(p).getAge() > a) {
      ...
   }
   else {
      ...
   }
}
...

Or in your example:

checkNotNull(someobject).doCalc();

Rather than Null Object Pattern -- which has its uses -- you might consider situations where the null object is a bug.

When the exception is thrown, examine the stack trace and work through the bug.


If you are using java8 or later go for the isNull(yourObject) from java.util.Objects.

Example:-

String myObject = null;

Objects.isNull(myObject); //will return true

Usage: The below code returns a non null value (if the name is not null then that value will be returned else the default value will be returned).

final String name = "Jobin";
String nonNullValue = Optional.ofNullable(name).filter(Objects::nonNull).orElse("DefaultName");

Asking that question points out that you may be interested in error handling strategies. How and where to handle errors is a pervasive architectural question. There are several ways to do this.

My favorite: allow the Exceptions to ripple through - catch them at the 'main loop' or in some other function with the appropriate responsibilities. Checking for error conditions and handling them appropriately can be seen as a specialized responsibility.

Sure do have a look at Aspect Oriented Programming, too - they have neat ways to insert if( o == null ) handleNull() into your bytecode.


The Google collections framework offers a good and elegant way to achieve the null check.

There is a method in a library class like this:

static <T> T checkNotNull(T e) {
   if (e == null) {
      throw new NullPointerException();
   }
   return e;
}

And the usage is (with import static):

...
void foo(int a, Person p) {
   if (checkNotNull(p).getAge() > a) {
      ...
   }
   else {
      ...
   }
}
...

Or in your example:

checkNotNull(someobject).doCalc();

OK, I now this has been technically answered a million times but I have to say this because this is an un-ending discussion with Java programmers.

Sorry but I disagree will almost all of above. The reason we have to be testing for null in Java is because must Java programmers don’t know how to handle memory.

I say this because I have a long experience programming in C++ and we don’t do this. In other words, you don’t need to. And note that, in Java, if you hit a dangling pointer you get a normal exception; in C++ this exception normally is not caught and terminates the program.

Don’t want to do this? Then follow some simple rules ala C/C++.

Don’t instantiate things so easily, think that every "new" can get you in lots of trouble and FOLLOW these simple rules.

A class shall access memory in only 3 ways ->

  1. It can "HAVE" class members, and they will follow these rules:

    1. ALL "HAS" members are created "new" in the constructor.
    2. You will close /de allocate in destructor or equivalent close() function in Java for that same class and in NO other.

This means that you need to have in mind (just like Java does) who is the owner or parent of each resource and respect that ownership. An object is only deleted by the class who created it. Also ->

  1. Some members will be "USED" but not own or "HAVE". This are "OWN" in another class and passed as arguments to the constructor. Since these are owned by another class, we will NEVER delete or close this, only the parent can.

  2. A method in a class can also instantiate local objects for internal use which will NEVER pass out side of the class, or they should have been normal "has" objects.

Finally for all this to work, you need to have a disciplined design with classes in hierarchy form and making no cycles.

Under this design, AND following the above rules, there is no way that a child class in a hierarchy design will ever access a pointer which was destroyed, because that means that a parent was destroyed before a child, which the hierarchical acyclic design will not allow it.

Finally, also remember when starting your system you should build from top to bottom of the hierarchy and destroy bottom to top. You will never have a null pointer anywhere, or someone is violating the rules.


There has a good way to check the null value from JDK. It is Optional.java that has a sea of methods to resolve these problems. Such as follow: `

  • Returns an {@code Optional} describing the specified value, if non-null,
    • otherwise returns an empty {@code Optional}.
    • @param the class of the value
    • @param value the possibly-null value to describe
    • @return an {@code Optional} with a present value if the specified value
    • is non-null, otherwise an empty {@code Optional}
public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}  `

`/

  • Return {@code true} if there is a value present, otherwise {@code false}. *

    • @return {@code true} if there is a value present, otherwise {@code false} */ public boolean isPresent() { return value != null; }

    /**

    • If a value is present, invoke the specified consumer with the value,
    • otherwise do nothing.
    • @param consumer block to be executed if a value is present
    • @throws NullPointerException if value is present and {@code consumer} is
    • null */ public void ifPresent(Consumer<? super T> consumer) { if (value != null) consumer.accept(value); }`

It is really, really useful to help javer.


This is the most common error occurred for most of the developers.

We have number of ways to handle this.

Approach 1:

org.apache.commons.lang.Validate //using apache framework

notNull(Object object, String message)

Approach 2:

if(someObject!=null){ // simply checking against null
}

Approach 3:

@isNull @Nullable  // using annotation based validation

Approach 4:

// by writing static method and calling it across whereever we needed to check the validation

static <T> T isNull(someObject e){  
   if(e == null){
      throw new NullPointerException();
   }
   return e;
}

It is possible to define util methods which handles nested null-checks in an almost pretty way with Java 8 lambdas.

void example() {
    Entry entry = new Entry();
    // This is the same as H-MANs solution 
    Person person = getNullsafe(entry, e -> e.getPerson());    
    // Get object in several steps
    String givenName = getNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.getGivenName());
    // Call void methods
    doNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.nameIt());        
}

/** Return result of call to f1 with o1 if it is non-null, otherwise return null. */
public static <R, T1> R getNullsafe(T1 o1, Function<T1, R> f1) {
    if (o1 != null) return f1.apply(o1);
    return null; 
}

public static <R, T0, T1> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, R> f2) {
    return getNullsafe(getNullsafe(o0, f1), f2);
}

public static <R, T0, T1, T2> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Function<T2, R> f3) {
    return getNullsafe(getNullsafe(o0, f1, f2), f3);
}


/** Call consumer f1 with o1 if it is non-null, otherwise do nothing. */
public static <T1> void doNullsafe(T1 o1, Consumer<T1> f1) {
    if (o1 != null) f1.accept(o1);
}

public static <T0, T1> void doNullsafe(T0 o0, Function<T0, T1> f1, Consumer<T1> f2) {
    doNullsafe(getNullsafe(o0, f1), f2);
}

public static <T0, T1, T2> void doNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Consumer<T2> f3) {
    doNullsafe(getNullsafe(o0, f1, f2), f3);
}


class Entry {
    Person getPerson() { return null; }
}

class Person {
    Name getName() { return null; }
}

class Name {
    void nameIt() {}
    String getGivenName() { return null; }
}

(This answer was first posted here.)


We have been using Apache libraries (Apache Commons) for this issue.

ObjectUtils.equals(object, null)

or

CollectionUtils.isEmpty(myCollection);

or

StringUtils.isEmpty("string");

I like the previous answer before, as a practice, of providing initial default values or empty sets for collections to minimize the need.

These can be simple uses that keep you from having NullPointerException or using an empty collection. This doesnt answer the question for what to do with the null object, but these provide some checks for basic validations of the object or collection.

Hope this helps.


Ultimately, the only way to completely solve this problem is by using a different programming language:

  • In Objective-C, you can do the equivalent of invoking a method on nil, and absolutely nothing will happen. This makes most null checks unnecessary, but it can make errors much harder to diagnose.
  • In Nice, a Java-derived language, there are two versions of all types: a potentially-null version and a not-null version. You can only invoke methods on not-null types. Potentially-null types can be converted to not-null types through explicit checking for null. This makes it much easier to know where null checks are necessary and where they aren't.

Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections

Example:

String foo;
...
if( StringUtils.isBlank( foo ) ) {
   ///do something
}

or (depending on what you need to check):

String foo;
...
if( StringUtils.isEmpty( foo ) ) {
   ///do something
}

The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.

Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)

public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
    Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
    return read(new StringReader(xml), true, validationEventHandler);
}

And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar)

Example on how to use this static classf from spring(org.springframework.util.Assert)

Assert.notNull(validationEventHandler,"ValidationHandler not Injected");

Functional approach may help to wrap the repetitive null checks and execute anonymous code like the below sample.

    BiConsumer<Object, Consumer<Object>> consumeIfPresent  = (s,f) ->{
        if(s!=null) {
            f.accept(s);
        }
    };

    consumeIfPresent.accept(null, (s)-> System.out.println(s) );
    consumeIfPresent.accept("test", (s)-> System.out.println(s));

    BiFunction<Object, Function<Object,Object>,Object> executeIfPresent  = (a,b) ->{
        if(a!=null) {
            return b.apply(a);
        }
        return null;
    };
    executeIfPresent.apply(null, (s)-> {System.out.println(s);return s;} );
    executeIfPresent.apply("test", (s)-> {System.out.println(s);return s;} );

Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException. It avoids any runtime NullPointerExceptions and supports us in developing clean and neat Java APIs or Applications. Like Collections and arrays, it is also a Container to hold at most one value.

Below are some useful link you can follow

https://www.mkyong.com/java8/java-8-optional-in-depth/

https://dzone.com/articles/java-8-optional-avoid-null-and


Wherever you pass an array or a Vector, initialise these to empty ones, instead of null. - This way you can avoid lots of checking for null and all is good :)

public class NonNullThing {

   Vector vectorField = new Vector();

   int[] arrayField = new int[0];

   public NonNullThing() {

      // etc

   }

}

Just don't ever use null. Don't allow it.

In my classes, most fields and local variables have non-null default values, and I add contract statements (always-on asserts) everywhere in the code to make sure this is being enforced (since it's more succinct, and more expressive than letting it come up as an NPE and then having to resolve the line number, etc.).

Once I adopted this practice, I noticed that the problems seemed to fix themselves. You'd catch things much earlier in the development process just by accident and realize you had a weak spot.. and more importantly.. it helps encapsulate different modules' concerns, different modules can 'trust' each other, and no more littering the code with if = null else constructs!

This is defensive programming and results in much cleaner code in the long run. Always sanitize the data, e.g. here by enforcing rigid standards, and the problems go away.

class C {
    private final MyType mustBeSet;
    public C(MyType mything) {
       mustBeSet=Contract.notNull(mything);
    }
   private String name = "<unknown>";
   public void setName(String s) {
      name = Contract.notNull(s);
   }
}


class Contract {
    public static <T> T notNull(T t) { if (t == null) { throw new ContractException("argument must be non-null"); return t; }
}

The contracts are like mini-unit tests which are always running, even in production, and when things fail, you know why, rather than a random NPE you have to somehow figure out.


All in all to avoid statement

if (object != null) {
    ....
}
  1. since java 7 you can use Objects methods:

    Objects.isNull(object)

    Objects.nonNull(object)

    Objects.requireNonNull(object)

    Objects.equals(object1, object2)

  2. since java 8 you can use Optional class (when to use)

object.ifPresent(obj -> ...); java 8

object.ifPresentOrElse(obj -> ..., () -> ...); java 9

  1. rely on method contract (JSR 305) and use Find Bugs. Mark your code with annotations @javax.annotation.Nullable and @javax.annotation.Nonnnul. Also Preconditions are available.

    Preconditions.checkNotNull(object);

  2. In special cases (for example for Strings and Collections) you can use apache-commons (or Google guava) utility methods:

public static boolean isEmpty(CharSequence cs) //apache CollectionUtils

public static boolean isEmpty(Collection coll) //apache StringUtils

public static boolean isEmpty(Map map) //apache MapUtils

public static boolean isNullOrEmpty(@Nullable String string) //Guava Strings

  1. When you need to assign default value when null use apache commons lang

public static Object defaultIfNull(Object object, Object defaultValue)


For utility classes, you can check that parameters are not null.

In all other cases, you may not have to. Use encapsulation as much as possible, thus reducing the places you feel tempted to check for null.


There has a good way to check the null value from JDK. It is Optional.java that has a sea of methods to resolve these problems. Such as follow: `

  • Returns an {@code Optional} describing the specified value, if non-null,
    • otherwise returns an empty {@code Optional}.
    • @param the class of the value
    • @param value the possibly-null value to describe
    • @return an {@code Optional} with a present value if the specified value
    • is non-null, otherwise an empty {@code Optional}
public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}  `

`/

  • Return {@code true} if there is a value present, otherwise {@code false}. *

    • @return {@code true} if there is a value present, otherwise {@code false} */ public boolean isPresent() { return value != null; }

    /**

    • If a value is present, invoke the specified consumer with the value,
    • otherwise do nothing.
    • @param consumer block to be executed if a value is present
    • @throws NullPointerException if value is present and {@code consumer} is
    • null */ public void ifPresent(Consumer<? super T> consumer) { if (value != null) consumer.accept(value); }`

It is really, really useful to help javer.


You can avoid most a lot to avoid NullPointerException by just following most of the others answers to the Question, I just want to add few more ways which have been introduced in Java 9 to handle this scenario gracefully and also showcase a few of the older ones can also be used and thus reducing your efforts.

  1. public static boolean isNull(Object obj)

    Returns true if the provided reference is null otherwise returns false.

    Since Java 1.8

  2. public static boolean nonNull(Object obj)

    Returns true if the provided reference is non-null otherwise returns false.

    Since Java 1.8

  3. public static <T> T requireNonNullElse?(T obj, T defaultObj)

    Returns the first argument if it is non-null and otherwise returns the non-null second argument.

    Since Java 9

  4. public static <T> T requireNonNullElseGet?(T obj, Supplier<? extends T> supplier)

    Returns the first argument if it is non-null and otherwise returns the non-null value of supplier.get().

    Since Java 9

  5. public static <T> T requireNonNull?(T obj, Supplier<String> messageSupplier)

    Checks that the specified object reference is not null and throws a customized NullPointerException otherwise.

    Since Java 1.8

Further details about the above functions can be found here.


In Java 8 you can use type T for local-variable/field/method-argument/method-return-type if it never assigned null (and do not check for null) or type Optional<T> if it can be null. Then use method map for processing T -> and method flatMap for processing T -> Optional<R>:

class SomeService {
    @Inject
    private CompanyDao companyDao;

    // return Optional<String>
    public Optional<String> selectCeoCityByCompanyId0(int companyId) {
        return companyDao.selectById(companyId)
                .map(Company::getCeo)
                .flatMap(Person::getHomeAddress)
                .flatMap(Address::getCity);
    }

    // return String + default value
    public String selectCeoCityByCompanyId1(int companyId) {
        return companyDao.selectById(companyId)
                .map(Company::getCeo)
                .flatMap(Person::getHomeAddress)
                .flatMap(Address::getCity)
                .orElse("UNKNOWN");
    }

    // return String + exception
    public String selectCeoCityByCompanyId2(int companyId) throws NoSuchElementException {
        return companyDao.selectById(companyId)
                .map(Company::getCeo)
                .flatMap(Person::getHomeAddress)
                .flatMap(Address::getCity)
                .orElseThrow(NoSuchElementException::new);
    }
}

interface CompanyDao {
    // real situation: no company for such id -> use Optional<Company> 
    Optional<Company> selectById(int id);
}

class Company {
    // company always has ceo -> use Person 
    Person ceo;
    public Person getCeo() {return ceo;}
}

class Person {
    // person always has name -> use String
    String firstName;
    // person can be without address -> use Optional<Address>
    Optional<Address> homeAddress = Optional.empty();

    public String getFirstName() {return firstName;}   
    public Optional<Address> getHomeAddress() {return homeAddress;}
}

class Address {
    //  address always contains country -> use String
    String country;
    //  city field is optional -> use Optional<String>
    Optional<String> city = Optional.empty();

    String getCountry() {return country;}    
    Optional<String> getCity() {return city;}
}

Asking that question points out that you may be interested in error handling strategies. How and where to handle errors is a pervasive architectural question. There are several ways to do this.

My favorite: allow the Exceptions to ripple through - catch them at the 'main loop' or in some other function with the appropriate responsibilities. Checking for error conditions and handling them appropriately can be seen as a specialized responsibility.

Sure do have a look at Aspect Oriented Programming, too - they have neat ways to insert if( o == null ) handleNull() into your bytecode.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to nullpointerexception

Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference Null pointer Exception on .setOnClickListener - java.lang.NullPointerException - setText on null object reference NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference Java 8 NullPointerException in Collectors.toMap NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

Examples related to null

getElementById in React Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? How to resolve TypeError: Cannot convert undefined or null to object Check if returned value is not null and if so assign it, in one line, with one method call How do I assign a null value to a variable in PowerShell? Using COALESCE to handle NULL values in PostgreSQL How to check a Long for null in java Check if AJAX response data is empty/blank/null/undefined/0 Best way to check for "empty or null value"