Skip to lesson

Why Optional exists

An Optional is a small box that either holds one value or is empty. A method returns Optional<T> when it may have nothing to give back, so the caller can see the "maybe" in the method's type instead of meeting a surprise null.

Recap: null and NullPointerException

Optional<T> is a container that either holds one value or is empty. It makes 'there may be no result' clear in a method's return type instead of returning null.

null is a special value that means "this reference points to no object". Any reference variable, such as a String or a Student, can hold it.

Calling a method on null crashes the program with a NullPointerException (NPE): there is no object to run the method on. String email = null; email.length(); stops right there.

The real problem is not null itself. It is that nothing in the code warns you. A method String findEmail(int roll) looks like it always returns an email. Only its documentation, or a crash in front of a user, tells you that it returns null when the roll number is unknown.

An NPE is the most common runtime error in Java programs, in college projects and in large company code alike.

The old way: a null check before every use

Before Java 8, the only defence was discipline: every caller writes if (email != null) { ... } before using the result. This works when everyone remembers.

Example 1 · The problem: a hidden null crashes the caller

HiddenNullDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class HiddenNullDemo {    static Map<Integer, String> emails = new HashMap<>();
    // Looks like it always returns an email. It returns null for unknown rolls.    static String findEmail(int roll) {        return emails.get(roll);    }
    public static void main(String[] args) {        emails.put(101, "aarav@college.in");        emails.put(102, "priya@college.in");
        String first = findEmail(101);        System.out.println("101: " + first.toUpperCase());
        String second = findEmail(205);        System.out.println("205 as text: " + second);        try {            System.out.println("205: " + second.toUpperCase());        } catch (NullPointerException e) {            System.out.println("205: crashed with " + e.getClass().getSimpleName());        }    }}
Output
101: AARAV@COLLEGE.IN
205 as text: null
205: crashed with NullPointerException

What this code does

  • Map.get returns null for a missing key, so findEmail(205) quietly returns null. Printing it with + even works and shows null.
  • The crash comes one step later, at second.toUpperCase(). The signature String findEmail(int roll) gave the caller no warning. The try/catch is here only so the program can show the error and finish.

But the compiler never reminds you. One forgotten check in one screen, and the app crashes for the one student whose email is missing. In a big codebase, you also cannot tell which methods may return null and which never do, so people either check everything or check nothing.

Optional: a box that may be empty

Java 8 added java.util.Optional<T>. An Optional<String> is either present (it holds one non-null String) or empty (it holds nothing). It never holds null inside.

An Optional is a box. A full Optional<String> holding Asha: isPresent() is true, get() gives Asha and orElse("guest") gives Asha. An empty Optional: isPresent() is false, get() throws NoSuchElementException and orElse("guest") gives guest.

Example 2 · The same lookup returning Optional

OptionalLookupDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.Optional;
public class OptionalLookupDemo {    static Map<Integer, String> emails = new HashMap<>();
    // The return type now says: there may be no email.    static Optional<String> findEmail(int roll) {        return Optional.ofNullable(emails.get(roll));    }
    public static void main(String[] args) {        emails.put(101, "aarav@college.in");        emails.put(102, "priya@college.in");
        Optional<String> first = findEmail(101);        Optional<String> second = findEmail(205);
        System.out.println("101: " + first);        System.out.println("205: " + second);        // String text = findEmail(101);   // does not compile: Optional<String> is not a String    }}
Output
101: Optional[aarav@college.in]
205: Optional.empty

What this code does

  • Optional.ofNullable turns the null from Map.get into an empty Optional. Nothing crashes, and the empty case is plainly visible as Optional.empty.
  • The commented line shows the real gain: the compiler refuses to treat an Optional<String> as a String, so the caller is forced to handle the empty case.
  • Why Optional: the return type now tells every caller that the value may be missing, and the compiler forces them to handle it. A plain String hides that risk until run time.

Now the method says the truth in its type: Optional<String> findEmail(int roll). A caller cannot treat the result as a String by mistake, because it is not a String. To get the text out, they must decide what happens when the box is empty. The next lessons show how. Optional was designed for one main job: the return type of a method that may find nothing, such as a search or a lookup. It is not meant to replace every variable that could be null.

  • Present: Optional[aarav@college.in] when printed.
  • Empty: Optional.empty when printed.
  • Two Optionals are equal when both are empty, or both hold equal values.

Three ways to create an Optional

Each factory method fits one situation. Pick it by asking: can this value be null here?

  1. Optional.of(value): you are sure the value is not null, for example a value you just found in a list.
  2. Optional.ofNullable(value): the value may be null, for example the result of map.get(key) or of an old library method. A null becomes an empty Optional.
  3. Optional.empty(): there is no value to return, for example at the end of a search loop that found nothing.

Example 3 · of, ofNullable and empty side by side

CreateOptionalDemo.javaJava
import java.util.Optional;
public class CreateOptionalDemo {    public static void main(String[] args) {        String city = "Pune";        String nickname = null;
        Optional<String> a = Optional.of(city);        Optional<String> b = Optional.ofNullable(city);   // may be null, here it is not        Optional<String> c = Optional.ofNullable(nickname);        Optional<String> d = Optional.empty();            // nothing to return
        System.out.println("of:               " + a);        System.out.println("ofNullable(city): " + b);        System.out.println("ofNullable(null): " + c);        System.out.println("empty:            " + d);
        System.out.println("a equals b? " + a.equals(b));        System.out.println("c equals d? " + c.equals(d));        System.out.println("blank is empty? " + Optional.of("").equals(Optional.empty()));    }}
Output
of:               Optional[Pune]
ofNullable(city): Optional[Pune]
ofNullable(null): Optional.empty
empty:            Optional.empty
a equals b? true
c equals d? true
blank is empty? false

What this code does

  • of and ofNullable give the same result for a real value. They differ only for null, where ofNullable returns an empty Optional.
  • Optionals compare by content: two present boxes with equal values are equal, and all empty boxes are equal. An empty String "" is still a value, so Optional.of("") is present, not empty.

Trap: Optional.of(null) throws NullPointerException

Optional.of(null) does not give you an empty box. It throws a NullPointerException immediately, on that line.

Example 4 · Trap: Optional.of(null) and the fix

OfNullTrapDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.Optional;
public class OfNullTrapDemo {    public static void main(String[] args) {        Map<String, Integer> marks = new HashMap<>();        marks.put("Kavya", 88);
        Integer rohanMarks = marks.get("Rohan");   // null: Rohan is not in the map        try {            Optional<Integer> wrong = Optional.of(rohanMarks);            System.out.println("wrong: " + wrong);        } catch (NullPointerException e) {            System.out.println("Optional.of(null) threw " + e.getClass().getSimpleName());        }
        Optional<Integer> right = Optional.ofNullable(rohanMarks);        System.out.println("ofNullable gives: " + right);        System.out.println("Kavya: " + Optional.ofNullable(marks.get("Kavya")));    }}
Output
Optional.of(null) threw NullPointerException
ofNullable gives: Optional.empty
Kavya: Optional[88]

What this code does

  • Optional.of requires a non-null value. Given null, it throws at once, so the line wrong: ... never prints.
  • Optional.ofNullable is the right tool for anything that comes out of Map.get. It returns an empty Optional for null and a present one for a real value.

This is deliberate. of means "I promise this is not null". If the promise is broken, Java fails fast, close to the cause, instead of letting the bug travel further. When the value really can be null, use ofNullable.

Fix the error

Fix Optional.of(null)

Read the real error, then pick the line that fixes it.

Round 1 of 2

The email can be null. Wrap it safely.

import java.util.Optional;
public class EmailBox {
public static void main(String[] args) {
String email = null;
Optional<String> box = Optional.of(email);
System.out.println(box.isPresent());
}
}

Error

Exception in thread "main" java.lang.NullPointerException
	at EmailBox.main(EmailBox.java:6)
Rule of thumb: values from Map.get, from fields that may be unset and from old APIs go through ofNullable. Values you have just checked or created go through of.

Example 5 · Real use: finding a UPI ID by phone number

UpiLookupDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Optional;
record UpiAccount(String phone, String upiId) {}
public class UpiLookupDemo {    static List<UpiAccount> accounts = new ArrayList<>();
    static Optional<String> findUpiId(String phone) {        for (UpiAccount acc : accounts) {            if (acc.phone().equals(phone)) {                return Optional.of(acc.upiId());   // found: the value is not null            }        }        return Optional.empty();                    // searched everything, nothing found    }
    public static void main(String[] args) {        accounts.add(new UpiAccount("9876543210", "rohan@okbank"));        accounts.add(new UpiAccount("9123456780", "meera@upi"));
        System.out.println("9123456780 -> " + findUpiId("9123456780"));        System.out.println("9000000000 -> " + findUpiId("9000000000"));    }}
Output
9123456780 -> Optional[meera@upi]
9000000000 -> Optional.empty

What this code does

  • A search loop is the classic place for Optional: return Optional.of(...) the moment the item is found, and Optional.empty() after the loop when nothing matched.
  • A payments screen that calls findUpiId now knows from the type alone that the phone number may not be registered.

Next step

Check your understanding

12 quick questions