Ah - the elusive null pointer exception; a developers worst enemy?

Coming from a C# background, I adored the simplistic syntax when it came to better null handling.

Null coalescing operator
var y = x ?? -1;

In layman’s terms, “If x is not null return that, otherwise, return -1

Null conditional operator
var city = country?.getState()?.getCity();

In layman’s terms, “If country is not null and getState() does not return null, return the value of the getCity() method, otherwise, return null

Java unfortunately does not have support for these operators. However, starting in Java 8, the Optional object provides a decent alternative.

Using Optional, we can rewrite the above statements as follows:

Null coalescing operator
var y = Optional.ofNullable(x).orElse(-1);
Null conditional operator
var city = Optional.ofNullable(country)
         .map(c -> c.getState())
         .map(s -> s.getCity())
         .orElse(null);

With the Optional class comes lots of flexibility, with a fluent syntax, which perhaps I will cover more in future posts.