Java Reference
In-Depth Information
The following snippet of code obtains a stream of strings by splitting a string using a regular expression (“ , ”).
The matched strings are printed on the standard output.
String str = "Ken,Jeff,Lee";
Pattern.compile(",")
.splitAsStream(str)
.forEach(System.out::println);
Ken
Jeff
Lee
Representing an Optional Value
In Java,
null
is used to represent “nothing” or an “empty” result. Most often, a method returns
null
if it does not have
a result to return. This has been a source of frequent
NullPointerException
in Java programs. Consider printing the
year of birth of a person, like so:
Person ken = new Person(1, "Ken", Person.Gender.MALE, null, 6000.0);
int year = ken.getDob().getYear(); // Throws a NullPointerException
System.out.println("Ken was born in the year " + year);
The code throws a
NullPointerException
at runtime. The problem is in the return value of the
ken.getDob()
method that returns
null
. Calling the
getYear()
method on a
null
reference results in the
NullPointerException
.
So, what is the solution? In fact, there is no real solution to this. Java 8 has introduced an
Optional<T>
class in the
java.util
package to deal with
NullPointerException
gracefully. Methods that may return nothing should return an
Optional
instead of
null
.
An
Optional
is a wrapper for a non-null value that may or may not contain a non-null value. Its
isPresent()
method returns true if it contains a non-null value, false otherwise. Its
get()
method returns the non-null value if
it contains a non-null value, and throws a
NoSuchElementException
otherwise. This implies that when a method
returns an
Optional
, you must, as a practice, check if it contains a non-null value before asking it for the value. If
you use the
get()
method before making sure it contains a non-null value, you may get a
NoSuchElementException
instead of getting a
NullPointerException
. This is why I said in the previous paragraph that there is no real solution
to the
NullPointerException
. However, returning an
Optional
is certainly a better way to deal with nulls as
developers will get used to using the
Optional
objects in the way they are designed to be used.
How do you create an
Optional<T>
object? The
Optional<T>
class provides three static factory methods to create
its objects.
<T> Optional<T> empty()
: Returns an empty
Optional
. That is, the
Optional<T>
returned
from this method does not contain a non-null value.
•
<T> Optional<T> of(T value)
: Returns an
Optional
containing the specified
value
as the
non-null value. If the specified value is
null
, it throws a
NullPointerException
.
•
<T> Optional<T> ofNullable(T value)
: Returns an
Optional
containing the specified
value
if the
value
is non-null. If the specified
value
is
null
, it returns an empty
Optional
.
The following snippet of code shows how to create
Optional
objects:
•
// Create an empty Optional
Optional<String> empty = Optional.empty();