Skip to content

Optional Results

The Course
•
25 min study

Intermediate's repository used null to mean “not found.” Optional makes that possible absence visible in the return type. It represents zero or one value. Use it for a query whose missing result is ordinary, while keeping malformed input and programming errors separate.

Understand the contract

Optional.of(value) contains a known nonnull value; Optional.empty() contains none. Optional.ofNullable(value) converts an existing possibly-null reference into that representation. Import Optional from java.util. A method returning Optional must return an Optional object, never null itself. Optional.of(null) throws NullPointerException at once, so use ofNullable whenever the reference might be null.

Optional<T> uses the generic type syntax you already know: T is the type of its possible contained value. isPresent() asks whether one exists, while isEmpty() asks the opposite. For a focused branch you can test isPresent before using get; for transformation or display, map and a fallback usually make the policy clearer.

map transforms a present value and leaves an empty Optional empty. orElse supplies a default value when empty. Neither changes the original object. These operations resemble stream transformations, but Optional handles at most one value, not an arbitrary sequence. In the example, find is a small lookup with an explicit absent result.

Avoid calling get() unless presence is established; an empty Optional has nothing to return. orElseThrow() with no argument behaves exactly like get() but says in its name that it can throw, so modern code prefers it. A default should mean something honest: displaying "Unknown" is a presentation policy, whereas inventing a fake stored record would conceal missing data. Do not wrap every field and parameter automatically. A required constructor argument is usually validated directly, as before.

Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.

Predict, then run Java
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        System.out.println(find("A").map(String::length).orElse(0));
        System.out.println(find("missing").orElse("Unknown"));
    }

    static Optional<String> find(String id) {
        if ("A".equals(id)) {
            return Optional.of("Read");
        }
        return Optional.empty();
    }
}
Check your prediction
Text
4
Unknown

Trace a different case

orElse(fallback()) evaluates fallback() before the method call, even if a value is present. orElseGet takes a Supplier and invokes it only for absence. The lambda () -> fallback() has no parameters; its body is deferred. A visible print below illustrates the difference. In real code a fallback might be expensive; use the lazy form when that work should happen only on a miss.

Compare the boundary case Java
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        Optional<String> present = Optional.of("Saved");
        System.out.println(present.orElse(fallback()));
        System.out.println(present.orElseGet(() -> fallback()));
    }

    static String fallback() {
        System.out.println("Building default");
        return "New";
    }
}
Check your prediction
Text
Building default
Saved
Saved

Choose absence without inventing a value

A missing result is not a zero, an empty title or a fabricated object unless the API explicitly defines that meaning. Optional makes the ordinary no-result branch visible, but the caller still decides whether to display a fallback, skip work or report absence.

Trace a present value through map: Read becomes length 4, then orElse leaves 4 alone. Trace an empty Optional through the same chain: map never calls its function and orElse supplies the fallback. The shape stays at most one value throughout.

Keep required inputs separate. A null constructor dependency is invalid input to reject, not an ordinary missing lookup to wrap automatically. Also avoid calling get immediately after receiving an Optional: that would turn a visible absence contract back into an unhandled failure.

Debug a plausible mistake

Optional replaces a null check with questions about contents. Code that still treats the Optional reference like a nullable value compiles and runs, but it asks the wrong question.

Exercise

Repair the absence check

describe must print Found Read for A1 and Missing for B2. Predict what the current program prints before changing anything; the bug is not in the map. The supplied version compiles; its behavior is the problem.

Debugging workspace Java
import java.util.Map;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        Map<String, String> titles = Map.of("A1", "Read");
        System.out.println(describe(titles, "A1"));
        System.out.println(describe(titles, "B2"));
    }

    static String describe(Map<String, String> titles, String id) {
        Optional<String> title = Optional.ofNullable(titles.get(id));
        if (title != null) {
            return "Found " + title;
        }
        return "Missing";
    }
}
Hint 1: the idea

Two things are being confused: "is there an Optional?" and "is there a value inside it?". A method that returns Optional always returns an Optional object, empty or not. Look also at what "Found " + title prints for an Optional.

Hint 2: a first step

Ask the Optional about its contents instead of comparing the reference with null. map turns a present title into the message, and orElse supplies the text for the empty case.

Show one solution
Java
import java.util.Map;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        Map<String, String> titles = Map.of("A1", "Read");
        System.out.println(describe(titles, "A1"));
        System.out.println(describe(titles, "B2"));
    }

    static String describe(Map<String, String> titles, String id) {
        Optional<String> title = Optional.ofNullable(titles.get(id));
        return title.map(found -> "Found " + found).orElse("Missing");
    }
}

Expected output after repair:

Text
Found Read
Missing

The original printed Found Optional[Read] and Found Optional.empty. The check title != null is always true, because Optional.ofNullable never returns null; that is the point of the type. And "Found " + title printed the wrapper, not the value. map runs only for a present value, and orElse covers the empty case, so neither line can reach the wrong branch.

Build it yourself

Exercise

Optional Results: practice

Write firstNonblank(List<String>) returning an Optional of the first trimmed nonblank string. The list and its elements are nonnull. Return empty for an empty list or all blanks; preserve input order. Demonstrate [" ", " Read ", "Test"] gives Read and an empty list gives the display fallback None.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        // Add your implementation and checks below.
        System.out.println("Your workspace");
    }
}
Hint 1: the idea

An ordinary early-return loop is clearer than saving a candidate and a separate found flag.

Hint 2: a first step

Return Optional.of for the first qualifying value, and Optional.empty only after the loop finishes.

Show one solution
Java
import java.util.List;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        System.out.println(firstNonblank(List.of(" ", " Read ", "Test")).orElse("None"));
        System.out.println(firstNonblank(List.of()).orElse("None"));
    }

    static Optional<String> firstNonblank(List<String> values) {
        for (String value : values) {
            String normalized = value.trim();
            if (!normalized.isEmpty()) {
                return Optional.of(normalized);
            }
        }
        return Optional.empty();
    }
}

Expected output:

Text
Read
None

The early return Optional.of(normalized) is what keeps input order: the first qualifying value ends the search. Optional.empty() is returned only after the loop has seen every element, so "none found" is never reported too soon. The caller, not this method, chooses the display text None.

Change it and test again

Add all-blank and one-element cases. Replace the early return with a variable overwritten on every match: which case shows the method now returns the last match? For the fallback example, change present to Optional.empty and predict the extra line printed by orElseGet.

Explain before moving on

When is absence a normal result, and when should input be rejected? Explain why Optional.empty and Optional.of("") mean different things. Never use a default merely to avoid deciding what a missing value means.

Was this article helpful?

Your response is saved on this device.