Handling null values in Java can be quite annoying. Careless use of null can also be a source of a variety of bugs.
“I call it my billion-dollar mistake.” – Sir C. A. R. Hoare, on his invention of the null reference
“Null sucks.” – Doug Lea
There exists a few guidelines, workarounds and solutions for handling the different occurencess of null values and avoid nasty null pointer (exceptions), for example the Null Object Pattern with its defined neutral (null) behaviour. In the case of returning possible null values from a method or for instance a collection, Guava (Google Core Libraries for Java 1.6+) offers the class Optional.
An non-null Optional reference can be used as an replacement for a nullable object reference. It allows to distinguish between an object reference must be present and an object reference might be absent. An Optional is an immutable instance that may contain a non-null reference to another object. If the Optional doesn’t contain a non-null reference, it contains “nothing”. This nothing is called Absent, it’s never called null.
Use cases for this class are:
- as method return value, indicating that no result is available instead of returning null
- to distinguish between unknown and known to have no value
- to wrap nullable elements for storage in collections that does not support null
Use the static factory method Optional.of() to create a non-null Optional. This method fails fast if it’s called with a null parameter.
Optional longValue = Optional.of(3L); assertTrue(longValue.isPresent()); assertEquals(new Long(3L), longValue.get());
To create an Optional with a possible null value use Optional.fromNullable(). Optional.absent() results in an absent (null) value. Use get() to retrieve a present value (get fails fast with an absent value), you may also define default values with or(someValue) (if value is absent) or retrieve null as return value with orNull(). Guava offers a nice fluent API as usual.
assertFalse(Optional.absent().isPresent()); assertFalse(Optional.fromNullable(null).isPresent()); assertEquals("foobar", Optional.fromNullable(null).or("foobar")); assertNull(Optional.fromNullable(null).orNull());
Further informations can be found in the documentation. Be aware that Optional is still marked as @Beta. So it might change in future releases.