orElse, orElseGet and orElseThrow
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Most of the time you want a plain value out of an Optional, not a box. The orElse family gives you the value when it is present, and in the empty case either a default or an exception, in one call and with no get().
orElse: a ready default value
orElse(other) returns the value inside the Optional, or other when it is empty. The result is a plain T, not an Optional, so you can use it straight away: String name = findName(roll).orElse("Guest");.
Example 1 · orElse: a default for missing values
import java.util.HashMap;import java.util.Map;import java.util.Optional;
public class OrElseDemo { static Map<Integer, String> nicknames = new HashMap<>();
static Optional<String> findNickname(int roll) { return Optional.ofNullable(nicknames.get(roll)); }
public static void main(String[] args) { nicknames.put(21, "Chintu");
String a = findNickname(21).orElse("Guest"); String b = findNickname(22).orElse("Guest"); System.out.println("Hi " + a); System.out.println("Hi " + b);
int bonus = Optional.<Integer>empty().orElse(0); System.out.println("Bonus marks: " + bonus);
String forOldCode = findNickname(30).orElse(null); System.out.println("For old code: " + forOldCode); }}Hi Chintu Hi Guest Bonus marks: 0 For old code: null
What this code does
orElsereturns a plainString(orintafter unboxing), so the result is used directly with noget()and noif.orElse(null)turns an empty Optional back intonull. It exists for passing values to older code that expectsnull; do not use it to escape Optional everywhere.
Use it when the default is a simple, ready value: a constant such as "Guest", 0 or "N/A", or a variable you already have. Old code that expects null can get it with orElse(null), but only at the edge where you talk to that code.
orElseGet: build the default only when needed
orElseGet(supplier) takes a lambda instead of a value. A Supplier<T> is a functional interface whose method takes nothing and returns a value: () -> buildDefault().
Example 2 · orElseGet runs the supplier only when empty
import java.util.Optional;
public class OrElseGetDemo { static String defaultTheme() { System.out.println(" (building default theme)"); return "light"; }
public static void main(String[] args) { Optional<String> saved = Optional.of("dark"); Optional<String> notSaved = Optional.empty();
System.out.println("User 1:"); String t1 = saved.orElseGet(() -> defaultTheme()); System.out.println(" theme = " + t1);
System.out.println("User 2:"); String t2 = notSaved.orElseGet(() -> defaultTheme()); System.out.println(" theme = " + t2); }}User 1: theme = dark User 2: (building default theme) theme = light
What this code does
- For user 1 the Optional holds
dark, so the supplier is never called and the "building" line never prints. - For user 2 the Optional is empty, so Java calls the supplier
() -> defaultTheme()and returns its result.OrElseGetDemo::defaultThemewould work the same way.
Java calls the supplier only when the Optional is empty. When a value is present, the supplier is never run. This is called lazy evaluation: the work is done only if its result is actually needed.
Trap: orElse runs its argument every time
Java always works out a method's arguments before it calls the method. So in findUser(id).orElse(loadFromDatabase(id)), loadFromDatabase(id) runs first, every time, even when findUser found the user and the database result is thrown away. This is eager evaluation.
Example 3 · Trap: orElse calls the database every time
import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Optional;
public class EagerTrapDemo { static Map<Integer, String> cache = new HashMap<>(); static int dbCalls = 0;
static Optional<String> findInCache(int roll) { return Optional.ofNullable(cache.get(roll)); }
static String loadFromDatabase(int roll) { dbCalls++; // pretend this is a slow query return "Student-" + roll; }
public static void main(String[] args) { cache.put(1, "Aarav"); cache.put(2, "Bhumi"); cache.put(3, "Chetan"); List<Integer> rolls = List.of(1, 2, 3);
for (int roll : rolls) { findInCache(roll).orElse(loadFromDatabase(roll)); } System.out.println("orElse: " + dbCalls + " database calls");
dbCalls = 0; for (int roll : rolls) { findInCache(roll).orElseGet(() -> loadFromDatabase(roll)); } System.out.println("orElseGet: " + dbCalls + " database calls");
String fourth = findInCache(4).orElseGet(() -> loadFromDatabase(4)); System.out.println(fourth + ", total now " + dbCalls); }}orElse: 3 database calls orElseGet: 0 database calls Student-4, total now 1
What this code does
- All three rolls are in the cache, yet
orElse(loadFromDatabase(roll))made 3 database calls: Java evaluates the argument beforeorElseeven starts, and the result is thrown away. orElseGet(() -> loadFromDatabase(roll))passes a lambda instead of a result. The database is called only for roll 4, the one cache miss.
With a constant this costs nothing. With a database query, a network call or a big calculation, it wastes time on every lookup. It can also be a real bug: orElse(createNewAccount(phone)) creates an account even for users who already have one. The fix is one word: orElseGet(() -> loadFromDatabase(id)). Now the call happens only in the empty case.
Predict the output
Predict how often the default is built
Each program counts the calls to load(). What does it print?
Round 1 of 3
The box is full. How many times does load() run?
orElseGet.orElseThrow: when a missing value is an error
Sometimes "not found" is not normal. A payment for an order id that does not exist should stop with a clear error, not continue with a default.
Example 4 · orElseThrow: plain and with a custom exception
import java.util.List;import java.util.NoSuchElementException;import java.util.Optional;
class RollNotFoundException extends RuntimeException { RollNotFoundException(int roll) { super("No student with roll number " + roll); }}
public class OrElseThrowDemo { static List<String> names = List.of("Ishaan", "Jaya", "Kiran");
static Optional<String> findByRoll(int roll) { if (roll >= 1 && roll <= names.size()) { return Optional.of(names.get(roll - 1)); } return Optional.empty(); }
public static void main(String[] args) { System.out.println(findByRoll(2).orElseThrow());
try { findByRoll(9).orElseThrow(); } catch (NoSuchElementException e) { System.out.println("Plain: " + e.getMessage()); }
try { findByRoll(9).orElseThrow(() -> new RollNotFoundException(9)); } catch (RollNotFoundException e) { System.out.println("Custom: " + e.getMessage()); } }}Jaya Plain: No value present Custom: No student with roll number 9
What this code does
orElseThrow()(Java 10) returns the value or throwsNoSuchElementException: No value present, exactly likeget(), but the name makes the possible exception obvious.orElseThrow(() -> new RollNotFoundException(9))throws your own exception with a message that says what went wrong. The lambda runs only in the empty case, so no exception object is built when the student exists.
orElseThrow() with no argument (Java 10) returns the value or throws NoSuchElementException. It does exactly what get() does, but its name says so, which is why it is preferred over get(). orElseThrow(() -> new OrderNotFoundException(id)) throws your own exception with a helpful message; the lambda is a Supplier of the exception, so the exception object is created only when needed.
Choosing one: orElse versus orElseGet versus orElseThrow
All three give back a plain value when the Optional is present. They differ only in the empty case.
Example 5 · Real use: all three in a shop payment
import java.util.HashMap;import java.util.Map;import java.util.Optional;
record Prefs(String language, boolean smsAlerts) { static Prefs defaults() { System.out.println(" (creating default prefs)"); return new Prefs("English", true); }}
public class ShopPaymentDemo { static Map<String, Integer> coupons = new HashMap<>(); static Map<String, Integer> wallets = new HashMap<>(); static Map<String, Prefs> prefs = new HashMap<>();
static void pay(String phone, String coupon, int bill) { int discount = Optional.ofNullable(coupons.get(coupon)).orElse(0); int balance = Optional.ofNullable(wallets.get(phone)) .orElseThrow(() -> new IllegalStateException("No wallet for " + phone)); Prefs p = Optional.ofNullable(prefs.get(phone)).orElseGet(Prefs::defaults);
int toPay = bill - discount; System.out.println(phone + ": pay Rs " + toPay + " of Rs " + balance + ", receipt in " + p.language() + (p.smsAlerts() ? " by SMS" : "")); }
public static void main(String[] args) { coupons.put("FEST20", 20); wallets.put("9811100001", 500); wallets.put("9811100002", 80); prefs.put("9811100001", new Prefs("Hindi", false));
pay("9811100001", "FEST20", 120); pay("9811100002", "NOCODE", 60); try { pay("9811100003", "FEST20", 90); } catch (IllegalStateException e) { System.out.println("Payment failed: " + e.getMessage()); } }}9811100001: pay Rs 100 of Rs 500, receipt in Hindi (creating default prefs) 9811100002: pay Rs 60 of Rs 80, receipt in English by SMS Payment failed: No wallet for 9811100003
What this code does
- Each method matches its case: a missing coupon is normal, so
orElse(0); a missing wallet is an error, soorElseThrow; default preferences are a new object, soorElseGet(Prefs::defaults)builds them only when needed. - For the first phone, saved preferences exist and "creating default prefs" never prints. For the third phone the wallet check throws first, so the rest of
paynever runs.
orElse(value): the default is a constant or already computed. Always evaluated.orElseGet(() -> ...): the default costs time, calls a database or has side effects. Evaluated only when empty.orElseThrow(() -> new XException(...)): a missing value is an error the caller must hear about.orElseThrow(): same asget(), but the name warns the reader.
Next step
Check your understanding
12 quick questions