How to avoid object != null condition check in Java?

0 votes
asked Jan 18, 2019 by Hitesh Garg (783 points)  

We were having a lot of NullPointerExceptions in our system due to which we end up having a lot of object != null conditions in our code.

Although some places we are sure that the Null pointer will never be thrown from a certain section of code but when someone else is implementing the code then we are not sure whether it will throw Null pointer or not and then we end up having the same condition again, which is completely useless.

Is there any other alternative for that?

For example:

if (someobject != null) {

1 Answer

0 votes
answered Feb 5, 2020 by Hitesh Garg (783 points)  
Best answer

Java 8 Optional

Java 8 comes with a new class Optional that solves some of the null checking problem.
It makes the intent of the code clear that the value can or can not be present and the person calling the value should consider that.


public static Optional<String> find(@NotNull String name) {
      if (name.equals("Codingeek")) {
         return Optional.of("Success");
   return Optional.empty();

// Prints "Success"
    .ifPresentOrElse(System.out::println, () -> System.out.println("It is empty"));

// Prints "It is empty"
    .ifPresentOrElse(System.out::println, () -> System.out.println("It is empty"));

Using @Nullable and @NotNull

If you are planning to use some IDE with good Java suppport then these annotations can be used as IDEs identify these annotations and dont allow you to do unnecessary checks or miss important checks.

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

// Intellij will complain about this and will inform
// you about the unnecessary check
  if(hello() != null) {


// Wont compile in Intellij
@Nullable public static String hello() {return "Hello World";}

The same things happen when you use @NotNull annotation with the parameters and inside the method, you can be sure that this value is never null. Example

void someMethod(@NotNull someParameter) { }