Course contentsShow
← Java
Lesson 1773 of 2,87037. Optional for Null SafetyFree lesson

The get() Method: Extracting the Value

Understand how get() retrieves the wrapped value, but throws NoSuchElementException if the Optional is empty.

The get() Method: Extracting the Value

You'll learn how to extract the wrapped value from an Optional—and why doing so carelessly can backfire.

Now that you've checked whether an Optional contains a value using isPresent() or isEmpty(), you might want to actually retrieve that value. The get() method does exactly that: it unwraps the value inside the Optional and returns it.

How get() Works

When you call get() on an Optional:

  • If the Optional contains a value, get() returns that value
  • If the Optional is empty, get() throws a NoSuchElementException

Think of an Optional like a locked box. The get() method forcefully opens the box to grab what's inside. If the box is empty, you get an exception—essentially a runtime error.

The Catch: You're Back to Square One

Here's the irony: if you blindly call get() without checking first, you've replaced one problem (NullPointerException from null) with another (NoSuchElementException from empty Optional). This defeats the purpose of using Optional in the first place.

Safe Usage Pattern

The typical pattern combines isPresent() with get():

Optional<String> optionalName = Optional.of("Alice");

if (optionalName.isPresent()) {
    String name = optionalName.get();  // Safe: we checked first
    // use name...
}

This works, but it's verbose. Later lessons will show you more elegant approaches like ifPresent(), orElse(), and map() that avoid get() altogether.

Key Takeaway: get() extracts the value from an Optional, but throws NoSuchElementException if empty—always verify presence with isPresent() before calling it, or use safer alternatives.