Creating and Inspecting Optionals
Use Optional.of, ofNullable, empty, isPresent, isEmpty, and get safely.
Creating and Inspecting Optionals is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Creating and Inspecting Optionals
This lesson covers the methods for creating Optional instances and inspecting their contents: isPresent, isEmpty, get, and safe alternatives.
Three Ways to Create an Optional
Create an Optional with Optional.of(), Optional.ofNullable(), or Optional.empty().
import java.util.Optional;
// 1. of: must be non-null
Optional<String> a = Optional.of("hello");
// 2. ofNullable: safely wraps null
String maybeNull = null;
Optional<String> b = Optional.ofNullable(maybeNull); // empty
Optional<String> c = Optional.ofNullable("world"); // present
// 3. empty: explicitly empty
Optional<Integer> empty = Optional.empty();
System.out.println(a.isPresent()); // true
System.out.println(b.isPresent()); // false
System.out.println(c.isEmpty()); // falseisPresent and isEmpty
isPresent() returns true if a value is present. isEmpty() (Java 11+) is the logical inverse.
import java.util.Optional;
Optional<String> opt = Optional.of("Java");
System.out.println(opt.isPresent()); // true
System.out.println(opt.isEmpty()); // false
Optional<String> empty = Optional.empty();
System.out.println(empty.isPresent()); // false
System.out.println(empty.isEmpty()); // true
// Prefer ifPresent() over if (isPresent()) get() — more readable
opt.ifPresent(v -> System.out.println(v.toUpperCase())); // JAVAget(): Use with Caution
get() returns the value or throws NoSuchElementException. Never call it without checking first.
import java.util.Optional;
Optional<String> opt = Optional.of("present");
System.out.println(opt.get()); // present
Optional<String> empty = Optional.empty();
try {
empty.get(); // NoSuchElementException!
} catch (java.util.NoSuchElementException e) {
System.out.println("No value!");
}
// Better pattern: always use orElse/orElseGet/orElseThrow
// instead of isPresent() + get()orElse and orElseGet
orElse(default) returns the default if empty. orElseGet(supplier) calls the supplier lazily — better for expensive defaults.
import java.util.Optional;
Optional<String> plan = Optional.empty();
// orElse: default value always evaluated
String basic = plan.orElse("FREE");
System.out.println(basic); // FREE
// orElseGet: supplier only called when empty (lazy)
String lazy = plan.orElseGet(() -> {
System.out.println("Computing default...");
return "FREE";
});
System.out.println(lazy); // Computing default... FREE
// When present, orElseGet supplier is NOT called
Optional.of("PRO").orElseGet(() -> {
System.out.println("Not called!");
return "FREE";
}); // silent — present, no computation neededorElseThrow
orElseThrow() throws NoSuchElementException or a custom exception if empty. Use it when absence is truly an error.
import java.util.Optional;
Optional<String> userId = Optional.empty();
// Default: throws NoSuchElementException
try {
userId.orElseThrow();
} catch (java.util.NoSuchElementException e) {
System.out.println("Empty!");
}
// Custom exception
try {
userId.orElseThrow(() -> new IllegalStateException("User ID required"));
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // User ID required
}ifPresent and ifPresentOrElse
These methods let you act on the value without extracting it. Clean for side effects.
import java.util.Optional;
Optional<String> username = Optional.of("alice");
// ifPresent: callback only when present
username.ifPresent(u -> System.out.println("Welcome, " + u));
// Welcome, alice
Optional<String> missing = Optional.empty();
// ifPresentOrElse (Java 9+): callback or else action
missing.ifPresentOrElse(
u -> System.out.println("Hello " + u),
() -> System.out.println("Anonymous user")
);
// Anonymous userChecking String Presence
A common use case: returning a default value when a config string is absent or blank.
import java.util.Optional;
static Optional<String> getConfig(String key) {
// Simulate config lookup
return Optional.ofNullable(System.getenv(key));
}
String port = getConfig("PORT").orElse("8080");
String host = getConfig("HOST").orElse("localhost");
System.out.println("Server: " + host + ":" + port);
// Server: localhost:8080 (when env vars not set)Optional.or() for Alternative Optionals
or() (Java 9+) returns the Optional itself if present, or another Optional provided by a supplier.
import java.util.Optional;
static Optional<String> findInCache(String key) { return Optional.empty(); }
static Optional<String> findInDatabase(String key) { return Optional.of("Alice"); }
Optional<String> result = findInCache("user:1")
.or(() -> findInDatabase("user:1"));
System.out.println(result.get()); // Alice
// Useful for fallback chains:
Optional<String> value = Optional.empty()
.or(() -> Optional.empty())
.or(() -> Optional.of("final fallback"));
System.out.println(value.get()); // final fallbackFilter for Conditional Presence
filter(predicate) keeps the value only if it satisfies the predicate, otherwise returns empty.
import java.util.Optional;
Optional<Integer> age = Optional.of(17);
Optional<Integer> adult = age.filter(a -> a >= 18);
System.out.println(adult.isPresent()); // false (17 is not >= 18)
Optional<Integer> age2 = Optional.of(25);
Optional<Integer> adult2 = age2.filter(a -> a >= 18);
System.out.println(adult2.get()); // 25
// Chain: find active premium user
Optional<User> premiumActive = findUser(id)
.filter(u -> "PRO".equals(u.plan()))
.filter(u -> u.isActive());Practical: User Lookup with Fallback
Combining isPresent, orElse, and ifPresentOrElse in a realistic user lookup scenario.
import java.util.Optional;
record User(long id, String name, String email) {}
static Optional<User> findById(long id) {
return id == 1 ? Optional.of(new User(1, "Alice", "alice@co.com"))
: Optional.empty();
}
static void displayUser(long id) {
findById(id).ifPresentOrElse(
u -> System.out.println("Found: " + u.name() + " <" + u.email() + ">"),
() -> System.out.println("User " + id + " not found")
);
}
displayUser(1); // Found: Alice <alice@co.com>
displayUser(99); // User 99 not foundQuick Check
What does orElseGet() do differently from orElse()?
Recap: Creating and Inspecting Optionals
Key takeaways:
- Optional.of() requires non-null; Optional.ofNullable() accepts null
- isPresent() / isEmpty() check presence; avoid calling get() without checking
- orElse() for cheap defaults; orElseGet() for expensive computed defaults
- orElseThrow() when absence is an error
- ifPresent() and ifPresentOrElse() for side effects without extracting the value
- filter() keeps value only if predicate passes; or() chains fallback Optionals
Frequently asked questions
Is the “Creating and Inspecting Optionals” lesson free?
Yes — the full text of “Creating and Inspecting Optionals” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Creating and Inspecting Optionals”?
Use Optional.of, ofNullable, empty, isPresent, isEmpty, and get safely. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Creating and Inspecting Optionals” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Why Optional Exists
- Creating and Inspecting Optionals
- Transforming Optionals: map and flatMap
- Optional Best Practices