Sub topic 4
Checking Whether a Value Is Present
An Optional can be in one of two states. It is either present, meaning it holds a value, or empty, meaning it holds nothing. Before you work with an Optional, you often need to know which state it is in. This chapter covers the two methods that tell you: isPresent and isEmpty.
A method is a named piece of code that you call on an object with a dot, like box.isPresent(). A boolean is a value that is either true or false. Both methods in this chapter return a boolean.
The Two States of an Optional
Think of an Optional as a small box. You can't see inside it. You can ask it a yes-or-no question: "Do you have something in you?"
An Optional is never in both states at once. It is also never "half full". Because the two states are opposites, the two methods always give opposite answers.
isPresent: "Is There a Value?"
isPresent() returns true when the Optional holds a value. It returns false when the Optional is empty. This method has been part of Java since Optional first appeared in Java 8.
isEmpty: "Is It Empty?"
isEmpty() asks the opposite question. It returns true when the Optional is empty and false when it holds a value. This method was added in Java 11. If you use an older Java version, it will not compile, and you should write !opt.isPresent() instead. The ! symbol means "not". It flips true to false and false to true.
Seeing Both Methods Side by Side
This program builds one full Optional and one empty Optional, then asks each one both questions.
import java.util.Optional;
public class PresenceDemo {
public static void main(String[] args) {
Optional<String> full = Optional.of("Ada");
Optional<String> empty = Optional.empty();
System.out.println(full.isPresent()); // true
System.out.println(full.isEmpty()); // false
System.out.println(empty.isPresent()); // false
System.out.println(empty.isEmpty()); // true
}
}Run it and you will see true, false, false, true. The table below sums up the results.
| Optional state | `isPresent()` | `isEmpty()` | Available since |
|---|---|---|---|
| Holds a value | `true` | `false` | isPresent: Java 8 |
| Empty | `false` | `true` | isEmpty: Java 11 |
Which One Should You Use?
Pick the one that matches the question in your head. That makes your code read like a sentence.
- If you mean "do this when we found something", write
if (opt.isPresent()). - If you mean "stop early when we found nothing", write
if (opt.isEmpty()).
Both work. opt.isEmpty() is easier to read than !opt.isPresent(), because a small ! is easy to miss.
A Worked Example: Looking Up Phone Numbers
Here is a more realistic case. A method looks up a person's phone number. Some people are not in the phone book, so the method returns an Optional<String>. The caller checks each result before using it.
import java.util.Map;
import java.util.Optional;
public class PhoneBook {
static final Map<String, String> PHONES =
Map.of("Ada", "555-0101", "Grace", "555-0199");
static Optional<String> findPhone(String name) {
return Optional.ofNullable(PHONES.get(name));
}
public static void main(String[] args) {
String[] people = {"Ada", "Linus", "Grace"};
for (String person : people) {
Optional<String> phone = findPhone(person);
if (phone.isPresent()) {
System.out.println(person + ": " + phone.get());
} else {
System.out.println(person + ": no number on file");
}
}
}
}The output is:
Ada: 555-0101
Linus: no number on file
Grace: 555-0199Let's walk through it step by step.
PHONES.get(name)returns the number, ornullif the name is missing.Optional.ofNullable(...)wraps that result. Anullbecomes an empty Optional.- In the loop,
phone.isPresent()tells us which state we have. - Only when the answer is
truedo we callphone.get()to read the number.
get() returns the value inside the Optional. If you call it on an empty Optional, it throws a NoSuchElementException, which is an error that stops your program. That is why the isPresent() check comes first. The next chapter shows safer ways to get the value out, which often make this check unnecessary.
Using isEmpty for an Early Exit
Sometimes the empty case is the one you want to handle first. A common pattern is the early return: you leave the method right away when something is missing, so the rest of the method only deals with the normal case.
import java.util.Optional;
public class Checkout {
static Optional<String> findCoupon(String code) {
if (code.equals("SAVE10")) {
return Optional.of("10% off");
}
return Optional.empty();
}
static String applyCoupon(String code) {
Optional<String> coupon = findCoupon(code);
if (coupon.isEmpty()) {
return "Coupon " + code + " is not valid";
}
return "Applied: " + coupon.get();
}
public static void main(String[] args) {
System.out.println(applyCoupon("SAVE10")); // Applied: 10% off
System.out.println(applyCoupon("FREE99")); // Coupon FREE99 is not valid
}
}The isEmpty() check works like a guard at the door. Once the code gets past it, we know the coupon exists, so calling get() is safe.
Edge Cases That Surprise Beginners
An Empty String Is Still a Value
"Present" means the box holds something. It does not mean the something is useful. An empty string "" or the number 0 is still a real value.
import java.util.Optional;
public class EdgeCases {
public static void main(String[] args) {
Optional<String> blank = Optional.of("");
System.out.println(blank.isPresent()); // true
Optional<Integer> zero = Optional.of(0);
System.out.println(zero.isPresent()); // true
Optional<String> fromNull = Optional.ofNullable(null);
System.out.println(fromNull.isEmpty()); // true
}
}Only a missing value makes an Optional empty. If you also want to treat "" as "nothing", you need an extra step. A later chapter shows how filter does this.
The Optional Itself Should Never Be null
An Optional variable should always point to an Optional object, either full or empty. A method that returns Optional should never return null. If it does, calling isPresent() on it crashes with a NullPointerException, the exact problem Optional was meant to solve.
Common Mistakes
Mistake 1: Checking the Optional Against null
Beginners used to null checks sometimes write this:
import java.util.Optional;
public class WrongCheck {
public static void main(String[] args) {
Optional<String> name = Optional.empty();
if (name != null) {
System.out.println("Found a name!"); // prints, but no name exists
}
if (name.isPresent()) {
System.out.println("This line does not print");
}
}
}The first check asks "does the box exist?" The box does exist, so the message prints, even though the box is empty. Always ask the box about its contents with isPresent() or isEmpty().
Mistake 2: Comparing with Optional.empty()
Writing if (name == Optional.empty()) happens to work today, because Java reuses one shared empty object. That is a hidden detail you should not depend on. isEmpty() says what you mean and always works.
Mistake 3: Calling get Without Checking
Calling get() on an Optional you have not checked is just as risky as using a variable that might be null. If you see get() with no check before it, treat it as a bug waiting to happen.
Mistake 4: Using isEmpty on Old Java
If your compiler says it "cannot find symbol: method isEmpty()", your project uses Java 8, 9, or 10. Switch to !opt.isPresent() or upgrade to Java 11 or later.
A Word on Style
The if (opt.isPresent()) { ... opt.get() ... } pattern is correct, and it is a good first step. It does look a lot like an old if (x != null) check, though. Optional has methods that handle both states in one call, with no separate check needed. You will meet them in the next chapters:
- Methods that supply a fallback value when the Optional is empty.
- Methods that run code only when a value exists.
Think of isPresent and isEmpty as basic tools. They are good for early returns, for tests, and for learning how Optional behaves. As you learn the other methods, you will need explicit checks less often.
Summary
| Question you want to ask | Method | Returns `true` when |
|---|---|---|
| Is there a value? | `isPresent()` | The Optional holds a value |
| Is there no value? | `isEmpty()` | The Optional is empty (Java 11+) |
| Is there no value? (Java 8–10) | `!isPresent()` | The Optional is empty |
Exercise
What does this code print, line by line? Optional<String> a = Optional.of(""); Optional<String> b = Optional.ofNullable(null); System.out.println(a.isPresent()); System.out.println(a.isEmpty()); System.out.println(b.isPresent());
Show answer
It prints true, then false, then false. The empty string "" is a real value, so a is present and not empty. Optional.ofNullable(null) creates an empty Optional, so b.isPresent() returns false.
Exercise
A teammate wrote this check: Optional<String> email = findEmail(id); if (email != null) { send(email.get()); }. Why can this crash, and how would you fix the condition?
Show answer
The condition only checks that the Optional object exists. It does not check whether a value is inside. If findEmail returns Optional.empty(), the condition is still true and email.get() throws NoSuchElementException. Fix it by writing if (email.isPresent()) { send(email.get()); }.
Exercise
Your project runs on Java 8. Rewrite the guard if (user.isEmpty()) { return "Guest"; } so that it compiles.
Show answer
Write if (!user.isPresent()) { return "Guest"; }. The isEmpty method was added in Java 11, so on Java 8 you negate isPresent with the ! operator.
Exercise
Write a method describe(Optional<Integer> age) that returns "Age unknown" when the Optional is empty and "Age: " followed by the number when it holds a value. Use an early return.
Show answer
static String describe(Optional<Integer> age) { if (age.isEmpty()) { return "Age unknown"; } return "Age: " + age.get(); } The isEmpty check handles the missing case first, so the get call afterward is always safe. On Java 8, use !age.isPresent() instead of age.isEmpty().