CKTIS / Java
Optional.get(): retrieving a value from Optional
`Optional.get()` returns the contained value when one is present. Calling it on an empty `Optional` throws `NoSuchElementException`.
Version: Java SE 21
Syntax
public T get()
T value = optional.get();Optional.get names the get method of java.util.Optional<T>. Optional.get() identifies the same no-argument method; call it on an instance, as in optional.get(), not on the class. The method has been available since Java 8. T is the type of the contained value.
When a value is present, get() returns it without changing the contents of the Optional. When the Optional is empty, get() does not return null; it throws the unchecked exception java.util.NoSuchElementException. Don't call get() blindly: a true result from isPresent() on the same instance confirms that a value is present.
If absence is expected, use orElse(fallback) to return a fallback or ifPresent(action) to run an action only when there is a value. If absence should be an error, the Java SE 21 documentation prefers the no-argument orElseThrow(), available since Java 10. It also throws NoSuchElementException; the overload that takes a supplier lets you choose the exception.
Examples
import java.util.NoSuchElementException;
import java.util.Optional;
public class OptionalGetDemo {
public static void main(String[] args) {
Optional<String> present = Optional.of("Ada");
Optional<String> empty = Optional.empty();
System.out.println(present.get());
try {
System.out.println(empty.get());
} catch (NoSuchElementException e) {
System.out.println("NoSuchElementException");
}
System.out.println(empty.orElse("Guest"));
}
}Result
Ada NoSuchElementException Guest
The first `get()` returns `Ada`. The second deliberately throws an exception, which the program catches so it can show that `orElse("Guest")` returns `Guest` instead.
Related lessons
- Java · Lesson 66 · Basic · Version: 2
- Java · Lesson 47 · Intermediate · Version: 2