AnyCompiler

The Optional Type

Optional<T> represents a value that might or might not be present, as an explicit alternative to returning null and hoping callers remember to check for it. Optional.of(value) wraps a present value, Optional.empty() represents an absent one, and orElse(fallback) unwraps it safely, supplying a default when nothing is there.

import java.util.Optional;

public class Main {
    static Optional<String> findUser(int id) {
        if (id == 1) {
            return Optional.of("Alice");
        }
        return Optional.empty();
    }

    public static void main(String[] args) {
        Optional<String> user = findUser(1);
        System.out.println(user.orElse("Unknown"));
        Optional<String> missing = findUser(2);
        System.out.println(missing.orElse("Unknown"));
    }
}
Output
Alice
Unknown

That's the foundation of Java: classes and interfaces for structuring code, inheritance and polymorphism for sharing behavior, generics and the Collections Framework for reusable, type-safe data structures, and lambdas and streams for Java's more modern, functional style. From here, the best next step is practice — pick a small program and build it, leaning on the compiler's static type checking to catch mistakes as you go.

Practice exercise

Write a method findUser(int id) that returns an Optional<String>: "Alice" if id is 1, otherwise empty. Call it with 2 and print the result with orElse("Unknown").

← static and finalMore lessons coming soon