Sub topic 4
Checking Whether a Value Is Present
An Optional is a box that either holds one value or holds nothing. Before you use what is inside, you often need to know which case you have. Java gives you two methods to ask that question: isPresent and isEmpty.
What the Two Methods Do
A method is a named action an object can perform. Both of these methods return a boolean. A boolean is a value that is either true or false.
isPresent()returnstruewhen the Optional holds a value.isEmpty()returnstruewhen the Optional holds nothing.
They always give opposite answers. If one is true, the other is false.
| Method | Optional holds a value | Optional is empty | Available since |
|---|---|---|---|
| `isPresent()` | `true` | `false` | Java 8 |
| `isEmpty()` | `false` | `true` | Java 11 |
isEmpty came later, in Java 11. Before Java 11, people wrote !opt.isPresent(). The ! sign means "not". This works, but it is easy to miss when you read the code quickly. isEmpty() says the same thing more plainly.
A Worked Example
Imagine a method that looks up a person's nickname. Some people have one and some do not. The method returns an Optional<String>, so the caller knows the answer might be missing.
import java.util.Optional;
public class PresenceDemo {
static Optional<String> findNickname(String name) {
if (name.equals("Margaret")) {
return Optional.of("Maggie");
}
return Optional.empty();
}
public static void main(String[] args) {
Optional<String> margaret = findNickname("Margaret");
Optional<String> tom = findNickname("Tom");
System.out.println(margaret.isPresent()); // true
System.out.println(margaret.isEmpty()); // false
System.out.println(tom.isPresent()); // false
System.out.println(tom.isEmpty()); // true
if (tom.isEmpty()) {
System.out.println("Tom has no nickname");
}
}
}Here is what happens step by step:
findNickname("Margaret")returns an Optional holding"Maggie".findNickname("Tom")returns an empty Optional.- The four
printlnlines show the answers from each method. - The
ifstatement runs its message only becausetomis empty.
Save this as PresenceDemo.java and run it with java PresenceDemo.java. You need Java 11 or later because the code uses isEmpty.
Choosing Between Them
Pick the method that matches the question you are asking.
- If you want to act when something exists, use
isPresent(). - If you want to act when something is missing, use
isEmpty().
Code reads best without the ! sign. Write if (result.isEmpty()) rather than if (!result.isPresent()).
A Common Mistake
Some beginners check an Optional against null, like this: if (nickname != null). This test is wrong. An Optional variable should never be null itself. An empty Optional is still a real object. It is just a box with nothing inside. A null check on it is always true and tells you nothing about the value.
Checking Is Only the First Step
isPresent and isEmpty tell you whether a value is there. They do not give you the value. Later chapters show safer ways to get the value out, such as supplying a default or running code only when a value exists. Those methods often remove the need for a separate check. For now, the point to remember is this: when you need a yes-or-no answer, ask the Optional directly.
Exercise
A method returns Optional<String> email = findEmail("sam"); and Sam has no email on file. What do email.isPresent() and email.isEmpty() return, and how would you print "No email" using the clearest check?
Show answer
email.isPresent() returns false and email.isEmpty() returns true. The clearest check is if (email.isEmpty()) { System.out.println("No email"); }, which avoids the ! sign that !email.isPresent() needs.
Exercise
Why is if (email != null) not a useful way to check whether an Optional holds a value?
Show answer
An Optional variable is an object even when it is empty, so it is never null if the method follows the rules. The test is always true and says nothing about whether a value is inside. Use isPresent() or isEmpty() instead.