Skip to lesson

Read a value from an Optional

Reading an Optional always means answering two questions: what to do when the value is there, and what to do when it is not. Java gives you methods that ask about the box, and methods that run your code only in the right case.

Ask about the box: isPresent and isEmpty

isPresent() returns true when the Optional holds a value. isEmpty() returns true when it holds nothing. They are exact opposites; isEmpty() was added in Java 11 so you can write if (result.isEmpty()) instead of if (!result.isPresent()).

Example 1 · isPresent and isEmpty

PresentEmptyDemo.javaJava
import java.util.Optional;
public class PresentEmptyDemo {    public static void main(String[] args) {        Optional<String> upi = Optional.of("kavya@okbank");        Optional<String> noUpi = Optional.empty();
        System.out.println("upi present?   " + upi.isPresent());        System.out.println("upi empty?     " + upi.isEmpty());        System.out.println("noUpi present? " + noUpi.isPresent());        System.out.println("noUpi empty?   " + noUpi.isEmpty());
        if (noUpi.isEmpty()) {            System.out.println("Please link a UPI ID before paying.");        }    }}
Output
upi present?   true
upi empty?     false
noUpi present? false
noUpi empty?   true
Please link a UPI ID before paying.

What this code does

  • isPresent() and isEmpty() always give opposite answers for the same Optional.
  • isEmpty() (Java 11) reads more naturally than !isPresent() when you want to act on the missing case.

These two only answer a yes or no question. They do not give you the value. They are handy when you need just that answer, for example "does this phone number already have an account?" before showing a sign-up form.

Run code only when there is a value: ifPresent

ifPresent(action) takes a lambda that receives the value. If the Optional is present, Java calls the lambda with the value. If it is empty, nothing happens at all.

Example 2 · ifPresent: act only when a value exists

FeeReminderDemo.javaJava
import java.util.List;import java.util.Optional;
public class FeeReminderDemo {    public static void main(String[] args) {        List<String> names = List.of("Aarav", "Sneha", "Vikram");        List<Optional<String>> phones = List.of(                Optional.of("9876500011"),                Optional.empty(),                Optional.of("9123400022"));
        for (int i = 0; i < names.size(); i++) {            String name = names.get(i);            phones.get(i).ifPresent(p ->                    System.out.println("Fee reminder for " + name + " sent to " + p));        }        System.out.println("Done");    }}
Output
Fee reminder for Aarav sent to 9876500011
Fee reminder for Vikram sent to 9123400022
Done

What this code does

  • For Sneha the Optional is empty, so ifPresent does nothing: no message, no error, no if written by us.
  • The lambda p -> ... receives the phone number itself, not the Optional. It can also use name, because name is never changed after it is set.

The lambda is a Consumer<T>: a functional interface whose method takes one value and returns nothing. So phone.ifPresent(p -> System.out.println("SMS sent to " + p)); sends the SMS only to students who have a phone number, with no if and no risk of a null.

Handle both cases: ifPresentOrElse

Often you need an answer in both cases: show the student's report, or show "not found". ifPresentOrElse(action, emptyAction), added in Java 9, takes two lambdas.

Example 3 · ifPresentOrElse: one of two actions

CouponDemo.javaJava
import java.util.Optional;
public class CouponDemo {    static void apply(Optional<Integer> discount) {        discount.ifPresentOrElse(                d -> System.out.println("Coupon applied: Rs " + d + " off"),                () -> System.out.println("No coupon for this order"));    }
    public static void main(String[] args) {        apply(Optional.of(50));        apply(Optional.empty());        apply(Optional.of(120));    }}
Output
Coupon applied: Rs 50 off
No coupon for this order
Coupon applied: Rs 120 off

What this code does

  • The first lambda is a Consumer<Integer> that gets the discount; the second is a Runnable, () -> ..., that runs only when the box is empty.
  • Exactly one lambda runs for each call. This is the Optional version of a full if/else.

The first is the same Consumer<T> as in ifPresent. The second is a Runnable: a functional interface whose method takes nothing and returns nothing, written as () -> .... Exactly one of the two runs, never both.

  • isPresent() / isEmpty(): a boolean answer, no value.
  • ifPresent(v -> ...): run code with the value, or do nothing.
  • ifPresentOrElse(v -> ..., () -> ...): run one of two blocks.
  • get(): hand over the value, or throw if there is none.

Trap: calling get on an empty Optional

get() returns the value inside the box. On an empty Optional it throws java.util.NoSuchElementException with the message "No value present". So get() brings back the very crash Optional was meant to prevent, just with a new name.

Example 4 · Trap: get on an empty Optional

GetTrapDemo.javaJava
import java.util.NoSuchElementException;import java.util.Optional;
public class GetTrapDemo {    public static void main(String[] args) {        Optional<String> seat = Optional.of("B2-34");        System.out.println("Seat: " + seat.get());
        Optional<String> waitlisted = Optional.empty();        try {            System.out.println("Seat: " + waitlisted.get());        } catch (NoSuchElementException e) {            System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());        }
        // Safe, but long: the check must never be forgotten        if (waitlisted.isPresent()) {            System.out.println("Seat: " + waitlisted.get());        } else {            System.out.println("Seat: not confirmed yet");        }    }}
Output
Seat: B2-34
NoSuchElementException: No value present
Seat: not confirmed yet

What this code does

  • get() on a present Optional returns the value. On an empty one it throws NoSuchElementException: No value present, which crashes the program just like an NPE would. The try/catch is here only to show the message.
  • The isPresent() then get() version is safe but no better than a null check. ifPresentOrElse says the same thing with no way to forget the check.

get() is safe only right after a check such as if (result.isPresent()). That check plus get works, but it is easy to forget the check, and it is no shorter than the old null check. Prefer ifPresent and ifPresentOrElse, or the default-value methods in the next lesson.

Find the bug

Find the unsafe get

Click the line that throws when the Optional is empty.

findEmail(205) finds nobody.

Round 1 of 3
If you see .get() on an Optional during a code review, look for the check right above it. No check means a possible crash.

Example 5 · Real use: find a student by roll number

RollLookupDemo.javaJava
import java.util.List;import java.util.Optional;
record Student(int roll, String name, int marks) {}
public class RollLookupDemo {    static List<Student> students = List.of(            new Student(11, "Aditi", 87),            new Student(12, "Farhan", 64),            new Student(14, "Lakshmi", 92));
    static Optional<Student> findByRoll(int roll) {        for (Student s : students) {            if (s.roll() == roll) {                return Optional.of(s);            }        }        return Optional.empty();    }
    static void showReport(int roll) {        findByRoll(roll).ifPresentOrElse(                s -> System.out.println(roll + ": " + s.name() + " scored " + s.marks()                        + (s.marks() >= 75 ? " (distinction)" : "")),                () -> System.out.println(roll + ": no student with this roll number"));    }
    public static void main(String[] args) {        showReport(14);        showReport(13);        showReport(12);
        boolean registered = findByRoll(11).isPresent();        System.out.println("Roll 11 registered? " + registered);    }}
Output
14: Lakshmi scored 92 (distinction)
13: no student with this roll number
12: Farhan scored 64
Roll 11 registered? true

What this code does

  • findByRoll returns Optional<Student>, so showReport cannot forget the "not found" case: ifPresentOrElse makes it write both branches.
  • isPresent() is the right tool when only the yes or no answer is needed, such as checking that a roll number is registered.

Next step

Check your understanding

12 quick questions