๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-8-optional-class
Java 8 Optional Class - GeeksforGeeks
May 16, 2026 - In the following example, we are using Optional. So, our program can execute without crashing. ... import java.util.Optional; // Driver Class public class OptionalDemo { // Main Method public static void main(String[] args) { String[] words = new String[10]; Optional<String> checkNull = Optional.ofNullable(words[5]); if (checkNull.isPresent()) { String word = words[5].toLowerCase(); System.out.print(word); } else System.out.println("word is null"); } }
Python map() function
Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.
Enumerate() in Python
Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.
Read JSON file using Python
Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.
Adding New Column to Existing DataFrame in Pandas
Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ optional-or-method-in-java-with-examples
Optional or() method in Java with examples - GeeksforGeeks
July 12, 2025 - Optional: Optional[9455] Optional by or(() -> Optional.of(100)) method: Optional[9455] Program 2: ... // Java program to demonstrate // Optional.or() method import java.util.*; import java.util.function.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print supplier System.out.println("Optional: " + op); try { // or supplier System.out.println("Optional by or(() ->" + " Optional.of(100)) method: " + op.or(() -> Optional.of(100))); } catch (Exception e) { System.out.println(e); } } }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ optional-of-method-in-java-with-examples
Optional of() method in Java with examples - GeeksforGeeks
July 12, 2025 - // Java program to demonstrate // Optional.of() method import java.util.*; public class GFG { public static void main(String[] args) { try { // create a Optional Optional<Integer> op = Optional.of(null); // print value System.out.println("Optional: " + op); } catch (Exception e) { System.out.println(e); } } }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ optional-ispresent-method-in-java
Optional isPresent() Method in Java - GeeksforGeeks
July 12, 2025 - This example finds out that a value is present inside a non-empty Optional. ... // Java program to demonstrate Optional.isPresent() // with a non-empty Optional import java.util.Optional; public class Geeks { public static void main(String[] args) { // Create an Optional with a non-null value Optional<Integer> optional = Optional.of(9455); // Print the Optional value System.out.println("Optional: " + optional); // Check if a value is present System.out.println("Is any value present: " + optional.isPresent()); } }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ optional-ofnullable-method-in-java-with-examples
Optional ofNullable() method in Java with examples - GeeksforGeeks
July 12, 2025 - The ofNullable() method of java.util.Optional class in Java is used to get an instance of this Optional class with the specified value of the specified type. If the specified value is null, then this method returns an empty instance of the Optional ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ optional-get-method-in-java-with-examples
Optional get() method in Java with examples - GeeksforGeeks
July 12, 2025 - // Java program to demonstrate // Optional.get() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println("Optional: " + op); try { // get the value System.out.println("Value of " + "this Optional: " + op.get()); } catch (Exception e) { System.out.println(e); } } }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ optional-filter-method-in-java-with-examples
Optional filter() method in Java with examples - GeeksforGeeks
July 12, 2025 - // Java program to demonstrate // Optional.filter() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println("Optional: " + op); try { // filter the value System.out.println("Filtered value " + "for odd or even: " + op .filter(num -> num % 2 == 0)); } catch (Exception e) { System.out.println(e); } } }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ optional-orelse-method-in-java-with-examples
Optional orElse() method in Java with examples - GeeksforGeeks
July 12, 2025 - The orElse() method of java.util.Optional class in Java is used to get the value of this Optional instance, if present. If there is no value present in this Optional instance, then this method returns the specified value.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ optional-orelsethrow-method-in-java-with-examples
Optional orElseThrow() method in Java with examples - GeeksforGeeks
July 12, 2025 - The orElseThrow() method of java.util.Optional class in Java is used to get the value of this Optional instance if present. If there is no value present in this Optional instance, then this method throws the exception generated from the specified ...
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ optional-class-guava-java
Optional Class | Guava | Java - GeeksforGeeks
July 11, 2025 - java.util.Optional offers the primitive-specialized versions OptionalInt, OptionalLong and OptionalDouble but Guava does not have these.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ optional-stream-method-in-java-with-examples
Optional stream() method in Java with examples - GeeksforGeeks
July 12, 2025 - Optional: Optional[9455] Getting the Stream: 9455 Program 2: ... // Java program to demonstrate // Optional.stream() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println("Optional: " + op); try { // get the Stream System.out.println("Getting the Stream:"); op.stream().forEach(System.out::println); } catch (Exception e) { System.out.println(e); } } }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ optional-empty-method-in-java-with-examples
Optional empty() method in Java with examples - GeeksforGeeks
July 12, 2025 - // Java program to demonstrate // Optional.empty() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<String> op = Optional.empty(); // print value System.out.println("Optional: " + op); } }
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ core java โ€บ guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - Java has a very fluent and elegant ... The newest Java version introduces the stream() method on the Optional class that allows us to treat the Optional instance as a Stream....
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 8 โ€บ docs โ€บ api โ€บ java โ€บ util โ€บ Optional.html
Optional (Java Platform SE 8 )
April 21, 2026 - If a value is present the result must include its string representation in the result. Empty and present Optionals must be unambiguously differentiable. ... Javaโ„ข Platform Standard Ed.
๐ŸŒ
DZone
dzone.com โ€บ coding โ€บ java โ€บ how to use optionals in java
How to Use Optionals in Java
June 16, 2020 - The get method should be reserved for use only when it is used within one of the Optional query methods (i.e., the populated or empty state of the Optional is checked first). Note that this orElseThrow method was introduced in JDK 9 as a way of reducing the confusion surrounding the use of the get method and should be favored over the get method. ... ...One of the few mistakes we made [in Java 8] was the naming of Optional.get(), because the name just invites people to call it without calling isPresent(), undermining the whole point of using Optional in the first place....
๐ŸŒ
Codingzap
codingzap.com โ€บ home โ€บ blog โ€“ programming & coding articles โ€บ optional parameters in java: 4 methods with codes explained
Optional Parameters in Java: 4 Methods With Codes Explained
March 26, 2026 - We all know about the Method Overloading concept in the Java language. Method overloading is a technique by which we can call the same method with a different number of arguments. As in the Method Overloading, we have the benefit of using a different number of arguments for the same method; this can be utilized to implement the Optional Parameter Concept.
๐ŸŒ
Develpreneur
develpreneur.com โ€บ home โ€บ introduction to the java optional class
Introduction to the Java Optional Class
November 15, 2022 - The optional class is essentially a container object, which may or may not contain a non-nullable value. One of the biggest problems with Java is that when we create variables or methods with return types, our intent is unclear if the value ...
๐ŸŒ
GitHub
gist.github.com โ€บ carefree-ladka โ€บ cc6426829c8865a45f727db7368e94fe
Complete Java Optional Guide with Best Practices ยท GitHub
Optional.empty() // Empty Optional Optional.of(value) // โš ๏ธ Throws NPE if null Optional.ofNullable(value) // โœ… Safe, recommended ยท isPresent() // true if value present isEmpty() // true if empty (Java 11+)
๐ŸŒ
Medium
medium.com โ€บ javarevisited โ€บ optional-class-in-java-8-making-your-code-more-clear-and-concise-62af0712910d
Optional Class in Java 8: Making Your Code More Clear and Concise . | by Hamza Nassour | Javarevisited | Medium
May 29, 2024 - It was introduced as a way to help ... and was added to Java as part of Java 8. Optional is a container that either contains a non-null value or nothing(empty Optional )....
Top answer
1 of 14
299

The main design goal of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.

This most closely matches use case #1 in the OP's question. Although, absence of a value is a more precise formulation than null since something like IntStream.findFirst could never return null.


For use case #2, passing an optional argument to a method, this could be made to work, but it's rather clumsy. Suppose you have a method that takes a string followed by an optional second string. Accepting an Optional as the second arg would result in code like this:

foo("bar", Optional.of("baz"));
foo("bar", Optional.empty());

Even accepting null is nicer:

foo("bar", "baz");
foo("bar", null);

Probably the best is to have an overloaded method that accepts a single string argument and provides a default for the second:

foo("bar", "baz");
foo("bar");

This does have limitations, but it's much nicer than either of the above.

Use cases #3 and #4, having an Optional in a class field or in a data structure, is considered a misuse of the API. First, it goes against the main design goal of Optional as stated at the top. Second, it doesn't add any value.

There are three ways to deal with the absence of a value in an Optional: to provide a substitute value, to call a function to provide a substitute value, or to throw an exception. If you're storing into a field, you'd do this at initialization or assignment time. If you're adding values into a list, as the OP mentioned, you have the additional choice of simply not adding the value, thereby "flattening" out absent values.

I'm sure somebody could come up with some contrived cases where they really want to store an Optional in a field or a collection, but in general, it is best to avoid doing this.

2 of 14
139

I'm late to the game but for what it's worth, I want to add my 2 Cents. They go against the design goal of Optional, which is well summarized by Stuart Marks's answer, but I'm still convinced of their validity (obviously).

Use Optional Everywhere

In General

I wrote an entire blog post about using Optional but it basically comes down to this:

  • design your classes to avoid optionality wherever feasibly possible
  • in all remaining cases, the default should be to use Optional instead of null
  • possibly make exceptions for:
    • local variables
    • return values and arguments to private methods
    • performance critical code blocks (no guesses, use a profiler)

The first two exceptions can reduce the perceived overhead of wrapping and unwrapping references in Optional. They are chosen such that a null can never legally pass a boundary from one instance into another.

Note that this will almost never allow Optionals in collections which is almost as bad as nulls. Just don't do it. ;)

Regarding your questions

  1. Yes.
  2. If overloading is no option, yes.
  3. If other approaches (subclassing, decorating, ...) are no option, yes.
  4. Please no!

Advantages

Doing this reduces the presence of nulls in your code base, although it does not eradicate them. But that is not even the main point. There are other important advantages:

Clarifies Intent

Using Optional clearly expresses that the variable is, well, optional. Any reader of your code or consumer of your API will be beaten over the head with the fact that there might be nothing there and that a check is necessary before accessing the value.

Removes Uncertainty

Without Optional the meaning of a null occurrence is unclear. It could be a legal representation of a state (see Map.get) or an implementation error like a missing or failed initialization.

This changes dramatically with the persistent use of Optional. Here, already the occurrence of null signifies the presence of a bug. (Because if the value were allowed to be missing, an Optional would have been used.) This makes debugging a null pointer exception much easier as the question of the meaning of this null is already answered.

More Null Checks

Now that nothing can be null anymore, this can be enforced everywhere. Whether with annotations, assertions or plain checks, you never have to think about whether this argument or that return type can be null. It can't!

Disadvantages

Of course, there is no silver bullet...

Performance

Wrapping values (especially primitives) into an extra instance can degrade performance. In tight loops this might become noticeable or even worse.

Note that the compiler might be able to circumvent the extra reference for short lived lifetimes of Optionals. In Java 10 value types might further reduce or remove the penalty.

Serialization

Optional is not serializable but a workaround is not overly complicated.

Invariance

Due to the invariance of generic types in Java, certain operations become cumbersome when the actual value type is pushed into a generic type argument. An example is given here (see "Parametric polymorphism").