Search⌘ K

Optional in Java 8: Part 1

Explore the Java 8 Optional class to understand how it wraps potentially null values, provides safer alternatives to traditional null checks, and offers utility methods for cleaner, more readable code. This lesson introduces the basics of creating and using Optional objects to improve null safety in Java applications.

What is an Optional?

Java 8 has introduced a new class Optional<T> in the java.util package.

The Optional<T> is a wrapper class that stores an object of type T. The object may or may not be present in the optional.

According to Oracle, “Java 8 Optional works as a container type for the value which is probably absent or null. Java Optional is a final class present in the java.util package.

Let us look at how things worked before optional was introduced. In the below example, we have a ...