Optional and Objects: Null Pointer Saviours!

No one loves Null Pointer Exceptions ! Is there a way we can get rid of them ? Maybe . . . 

Couple of techniques have been discussed in this post

  • Optional type (new in Java 8)
  • Objects class (old Java 7 stuff 😉 )

Optional type in Java 8

What is it?

  • A new type (class) introduced in Java 8
  • Meant to act as a ‘wrapper‘ for an object of a specific type or for scenarios where there is no object (null)

In plain words, its a better substitute for handling nulls (warning: it might not be very obvious at first !)

Basic Usage

It’a a type (a class) – so, how do I create an instance of it?

Just use three static methods in the Optional class

public static Optional<String> stringOptional(String input) {
return Optional.of(input);

Plain and simple – create an Optional wrapper containing the value. Beware – will throw NPE in case the value itself is null !

public static Optional<String> stringNullableOptional(String input) {
if (!new Random().nextBoolean()) {
input = null;
return Optional.ofNullable(input);

Slightly better in my personal opinion. There is no risk of an NPE here – in case of a null input, an empty Optional would be returned

public static Optional<String> emptyOptional() {
return Optional.empty();

In case you want to purposefully return an ’empty’ value. ’empty’ does not imply null

Alright – what about consuming/using an Optional?

public static void consumingOptional() {
Optional<String> wrapped = Optional.of("aString");
if (wrapped.isPresent()) {
System.out.println("Got string – " + wrapped.get());
else {
System.out.println("Gotcha !");

A simple way is to check whether or not the Optional wrapper has an actual value (use the isPresent method) – this will make you wonder if its any better than using if(myObj!=null) 😉  Don’t worry, I’ll explain that as well

public static void consumingNullableOptional() {
String input = null;
if (new Random().nextBoolean()) {
input = "iCanBeNull";
Optional<String> wrapped = Optional.ofNullable(input);

One can use the orElse which can be used to return a default value in case the wrapped value is null – the advantage is obvious. We get to avoid the the obvious verbosity of invoking ifPresent before extracting the actual value

public static void consumingEmptyOptional() {
String input = null;
if (new Random().nextBoolean()) {
input = "iCanBeNull";
Optional<String> wrapped = Optional.ofNullable(input);
() -> {
return "defaultBySupplier";

I was a little confused with this. Why two separate methods for similar goals ? orElse and orElseGet could well have been overloaded (same name, different parameter)

Anyway, the only obvious difference here is the parameter itself – you have the option of providing a Lambda Expression representing instance of a Supplier<T> (a Functional Interface)

How is using Optional better than regular null checks????

  • By and large, the major benefit of using Optional is to be able to express your intent clearly – simply returning a null from a method leaves the consumer in a sea of doubt (when the actual NPE occurs) as to whether or not it was intentional and requires further introspection into the javadocs (if any). With Optional, its crystal clear !
  • There are ways in which you can completely avoid NPE with Optional – as mentioned in above examples, the use of Optional.ofNullable (during Optional creation) and orElse and orElseGet (during Optional consumption) shield us from NPEs altogether

Another savior! (in case you can’t use Java 8)

Look at this code snippet

package com.abhirockzz.wordpress.npesaviors;
import java.util.Map;
import java.util.Objects;
public class UsingObjects {
String getVal(Map<String, String> aMap, String key) {
return aMap.containsKey(key) ? aMap.get(key) : null;
public static void main(String[] args) {
UsingObjects obj = new UsingObjects();
obj.getVal(null, "dummy");

What can possibly be null?

  • The Map object
  • The key against which the search is being executed
  • The instance on which the method is being called

When a NPE is thrown in this case, we can never be sure as to What is null?

Enter The Objects class

package com.abhirockzz.wordpress.npesaviors;
import java.util.Map;
import java.util.Objects;
public class UsingObjects {
String getValSafe(Map<String, String> aMap, String key) {
Map<String, String> safeMap = Objects.requireNonNull(aMap,
"Map is null");
String safeKey = Objects.requireNonNull(key, "Key is null");
return safeMap.containsKey(safeKey) ? safeMap.get(safeKey) : null;
public static void main(String[] args) {
UsingObjects obj = new UsingObjects();
obj.getValSafe(null, "dummy");

The requireNonNull method

  • Simply returns the value in case its not null
  • Throws a NPE will the specified message in case the value in null

Why is this better than if(myObj!=null)

The stack trace which you would see will clearly have the Objects.requireNonNull method call. This, along with your custom error message will help you catch bugs faster . . much faster IMO !

You can write your user defined checks as well e.g. implementing a simple check which enforces non-emptiness

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
public class RandomGist {
public static <T> T requireNonEmpty(T object, Predicate<T> predicate, String msgToCaller){
if (predicate.test(object)){
throw new IllegalArgumentException(msgToCaller);
return object;
public static void main(String[] args) {
//Usage 1: an empty string (intentional)
String s = "";
System.out.println(requireNonEmpty(Objects.requireNonNull(s), (s1) -> s1.isEmpty() , "My String is Empty!"));
//Usage 2: an empty List (intentional)
List list = Collections.emptyList();
System.out.println(requireNonEmpty(Objects.requireNonNull(list), (l) -> l.isEmpty(), "List is Empty!").size());
//Usage 3: an empty User (intentional)
User user = new User("");
System.out.println(requireNonEmpty(Objects.requireNonNull(user), (u) -> u.getName().isEmpty(), "User is Empty!"));
private static class User {
private String name;
public User(String name){
this.name = name;
public String getName(){
return name;

view raw


hosted with ❤ by GitHub

Don’t let NPEs be a pain in the wrong place. We have more than a decent set of tools at our disposal to better handle NPEs or eradicate them altogether !

Cheers! 🙂

About Abhishek

Loves Go, NoSQL DBs and messaging systems
This entry was posted in Java, Java SE and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s