0Pricing
Java Academy · Lesson

Creating and Inspecting Optionals

Use Optional.of, ofNullable, empty, isPresent, isEmpty, and get safely.

Creating and Inspecting Optionals

This lesson covers the methods for creating Optional instances and inspecting their contents: isPresent, isEmpty, get, and safe alternatives.

Three Ways to Create an Optional

Create an Optional with Optional.of(), Optional.ofNullable(), or Optional.empty().

import java.util.Optional;

// 1. of: must be non-null
Optional<String> a = Optional.of("hello");

// 2. ofNullable: safely wraps null
String maybeNull = null;
Optional<String> b = Optional.ofNullable(maybeNull); // empty
Optional<String> c = Optional.ofNullable("world");   // present

// 3. empty: explicitly empty
Optional<Integer> empty = Optional.empty();

System.out.println(a.isPresent()); // true
System.out.println(b.isPresent()); // false
System.out.println(c.isEmpty());   // false

All lessons in this course

  1. Why Optional Exists
  2. Creating and Inspecting Optionals
  3. Transforming Optionals: map and flatMap
  4. Optional Best Practices
← Back to Java Academy