Null Safety: Avoid Null Pointer Exception in Java

Tamer Ardal
5 min readOct 17, 2024

--

If you want to learn more about null checks, you can also read my previous post on Simplify Null Checks in Java: Writing Clean Code with Apache Commons Lang 3!

AI Generated by Canva

Checking nulls in Java is one of the basic issues that every programmer faces. However, sometimes these checks can make the code complex and difficult to read. The Optional class that comes with Java 8 is a great tool to solve this problem. In this article, we will look at what Optional is, how it is used, and how it can be useful in projects and also look at how you can check nulls Objects, Strings and Collections.

Problem of Null Pointer Exception

One of the most common errors in Java is the NullPointerException (NPE). It occurs when you try to perform an operation with a null reference, and to avoid this error we need to frequently check for nulls in the code:

if (object != null) {
// process
} else {
// error
}
if (myString == null || myString == ""){
// Null or empty
}

if (myString == null || myString.trim().isEmpty()) {
// String is either null, empty, or only contains whitespace
}

if(myList == null || myList.size() == 0){
// Null or empty
}

if (myObject == null) {
// Null
}

if (myObject != null) {
// Not null
}

Such controls can become very difficult to manage over time. But there is a solution for this that is available to us with Java 8.

Using Optional for Null Safety (Java 8+)

Starting with Java 8, the Optional class was introduced to handle potentially null values in a cleaner way. Optional can be used to avoid null pointer exceptions and make your null checks safer.

To use Optional, you wrap the object like this:

Optional<String> optionalName = Optional.ofNullable(inputName);

If inputName is null, optionalName will represent an empty Optional. You can then handle this with methods like orElse().

String name = Optional.ofNullable(inputName).orElse("John Doe");

Or if you want the throw exception, you need to handle like this:

String name = Optional.ofNullable(inputName).orElseThrow(() -> 
new ValidationException("Input can not be null."));

Also you can use conditionally perform actions if the value is not null:

Optional.ofNullable(inputName).ifPresent(name -> {
// Do something with the name
});

You can use ifPresent and orElse together:

Optional.ofNullable(inputName).ifPresentOrElse(name -> // Do something with the name
, () -> throw new SomeException());

Mapping With Optional

In Java, Optional class has map() method. If Optional is not empty, the map method takes a function, transforms the value in it and returns a new Optional. Or the other case, if Optional is empty this method do nothing and return empty Optional.

Integer age = Optional.ofNullable(person)
.map(Person::getAge)
.orElse(18);

What’s the Different Between of() and ofNullable()

There are 2 methods in Optional. of() and ofNullable(). There is an important difference between the two.

Optional.of()

This method never accept null value. If you use this with null value, it throws Null Pointer Exception. If you have a value that you know will never be null, using of() is the best option.

String name = "John Doe";
Optional<String> optionalName = Optional.of(name); // Works

String nullName = null;
Optional<String> optionalNull = Optional.of(nullName); // Throws NullPointerException!

Optional.ofNullable()

The Optional.ofNullable() method accepts both null and non-null values. If null is given as an argument, it returns an empty Optional. If a non-null value is given, it returns an Optional holding that value.

String name = "John Doe";
Optional<String> optionalName = Optional.ofNullable(name); // Works, returns Optional name.

String nullName = null;
Optional<String> optionalNull = Optional.ofNullable(nullName); // Returns Optional.empty().

Therefore, it is safest to use Optional.ofNullable() if you think a variable might be null. If you are absolutely sure that it will not be null, you can use Optional.of().

Using Objects Utility for General Null Checks (Java 7+)

Java 7 introduced the Objects utility class, which provides a clean way to handle null checks. The isNull() and nonNull() methods are particularly useful when you want to check object if is null:

if (Objects.isNull(myObject)) {
// Null or empty
}

if (Objects.nonNull(myObject)) {
// Not null or empty
}

If you want the object is required a value, you can use the requireNonNull method of the Objects class.

Objects.requireNonNull(myObject, "Object cannot be null");

If you want to assign a default value to an object in case it is null, you can use the requireNonNullElse() method like following.

Integer age = Objects.requireNonNullElse(age, 18);

Checking Strings for Null or Empty (Java 11+)

Especially when working with String values, we need to do a lot of null, empty or white spaces checking. In this case, we can easily do this like following:

if (Objects.isNull(myString) || myString.isBlank()) {
// String is either null, empty, or contains only whitespace characters
}

if (myString.isBlank()) {
// String is empty or contains only spaces
}

if (myString.isEmpty()) {
// String is empty
}

Checking Collections with isEmpty()

In Java, collections such as lists and maps also need to be checked for empty values. Collection interface provides the isEmpty() method, which can using like this:

if (myList.isEmpty()) {
// List is empty
}

if (myMap.isEmpty()) {
// Map is empty
}

In this way, we can do both checks at once and make the code cleaner.

Java’s standard classes provide powerful tools to handle null values efficiently and cleanly. Whether you use traditional checks, Optional, or the Objects class, you can write code that is both readable and safe from null pointer exceptions.

By leveraging these standard Java features, you can keep your codebase lightweight and maintainable without relying on third-party dependencies.

Thank you for reading my article! If you have any questions, feedback or thoughts you would like to share, I would love to hear them in the comments.

You can follow me on Medium for more information on this topic and my other posts. Don’t forget to clap my posts to help them reach more people!

Thank you! 👨‍💻🚀

To follow me on LinkedIn: https://www.linkedin.com/in/tamerardal/

Resources:

  1. https://www.educative.io/answers/what-is-objectsnonnull-in-java
  2. https://docs.oracle.com/javase/9/docs/api/java/util/Objects.html#requireNonNullElse-T-T-
  3. https://www.baeldung.com/java-optional

--

--

No responses yet