Class Declaration
To use the Optional class in your Java code, you first need to declare it. The Optional class is a generic type, which means you can specify the type of value it holds.
Let’s see how you can declare an Optional
Optional<String> optionalString = Optional.empty();
Optional<Integer> optionalInteger = Optional.of(10);
Optional<Double> optionalDouble = Optional.ofNullable(null);
In the above examples, we declare three different Optional instances:
1. `optionalString`: An empty Optional of type String, created using the `Optional.empty()` method.
2. `optionalInteger`: An Optional of type Integer, created using the `Optional.of(10)` method, which expects a non-null value.
3. `optionalDouble`: An Optional of type Double, created using the `Optional.ofNullable(null)` method, which allows a null value to be passed.
Program Using Optional Class in Java 8:
Let's look at a simple program that shows the use of the Optional class in Java 8:
Java
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
String[] words = new String[5];
words[0] = "Hello";
words[1] = "Optional";
words[2] = "Class";
words[3] = "in";
words[4] = "Java 8";
Optional<String> optionalWord = Optional.ofNullable(words[2]);
if (optionalWord.isPresent()) {
String word = optionalWord.get();
System.out.println("The word is: " + word);
} else {
System.out.println("No word found.");
}
Optional<String> emptyOptional = Optional.ofNullable(words[5]);
emptyOptional.ifPresent(word -> System.out.println("The word is: " + word));
}
}

You can also try this code with Online Java Compiler
Run Code
Output
The word is: Class
In this program, we have an array of words. We create an Optional instance `optionalWord` using the `Optional.ofNullable()` method, passing the word at index 2. We then check if the Optional contains a value using the `isPresent()` method. If a value is present, we retrieve it using the `get()` method & print it. Otherwise, we print "No word found."
We also create an empty Optional instance `emptyOptional` by passing an index that is out of bounds. We use the `ifPresent()` method to print the word if it exists. Since the index is out of bounds, no word will be printed.
Optional Class in Java 8 Methods
The Optional class in Java 8 provides a set of useful methods to work with optional values.
Let's discuss some of the commonly used methods:
1. `empty()`
Returns an empty Optional instance.
Optional<String> emptyOptional = Optional.empty();
2. `of(value)`
Returns an Optional with the specified non-null value. Throws NullPointerException if the value is null.
Optional<Integer> optionalInt = Optional.of(10);
3. `ofNullable(value)`
Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
Optional<String> optionalString = Optional.ofNullable(null);
4. `isPresent()`
Returns true if the Optional contains a value, otherwise false.
Optional<Double> optionalDouble = Optional.of(3.14);
boolean isPresent = optionalDouble.isPresent(); // true
5. `get()`
Returns the value if present, otherwise throws NoSuchElementException.
Optional<String> optionalString = Optional.of("Hello");
String value = optionalString.get(); // "Hello"
6. `ifPresent(consumer)`
Performs the specified action with the value if present.
Optional<Integer> optionalInt = Optional.of(10);
optionalInt.ifPresent(value -> System.out.println("Value: " + value));
7. `orElse(other)`
Returns the value if present, otherwise returns the specified other value.
Optional<String> optionalString = Optional.empty();
String value = optionalString.orElse("Default");
8. `orElseGet(supplier)`
Returns the value if present, otherwise invokes the specified supplier & returns its result.
Optional<Integer> optionalInt = Optional.empty();
int value = optionalInt.orElseGet(() -> 0);
Examples for Optional Class in Java 8:
1. Filtering values
Optional<Integer> optionalInt = Optional.of(10);
Optional<Integer> filteredOptional = optionalInt.filter(value -> value > 5);
System.out.println(filteredOptional.isPresent()); // true
In this example, we have an Optional containing the value 10. We use the `filter()` method to check if the value is greater than 5. Since the condition is true, the filtered Optional still contains the value.
2. Mapping values
Optional<String> optionalString = Optional.of("HELLO");
Optional<String> mappedOptional = optionalString.map(String::toLowerCase);
System.out.println(mappedOptional.get()); // "hello"
Here, we have an Optional containing the string "HELLO". We use the `map()` method to transform the value to lowercase using the `String::toLowerCase` method reference. The mapped Optional now contains the lowercase string "hello".
3. Chaining methods
Optional<Integer> optionalInt = Optional.of(10);
String result = optionalInt
.filter(value -> value > 5)
.map(value -> value * 2)
.map(value -> "The value is " + value)
.orElse("No value found");
System.out.println(result); // "The value is 20"
In this example, we chain multiple methods on an Optional. We start with an Optional containing the value 10. We first filter the value to check if it's greater than 5. If true, we map the value by multiplying it by 2. We then map the value again to create a string. Finally, we use `orElse()` to provide a default value if the Optional is empty. The result is the string "The value is 20".
Frequently Asked Questions
Can Optional be used with primitive types?
No, Optional is designed to work with reference types. However, Java provides specialized optional classes for primitives, such as OptionalInt, OptionalLong, & OptionalDouble.
Is it necessary to check if an Optional is present before accessing its value?
Yes, it is recommended to always check if an Optional contains a value using the isPresent() method before accessing the value with get(). Directly calling get() on an empty Optional will throw a NoSuchElementException.
Can Optional be used as a method parameter or field type?
While it is possible to use Optional as a method parameter or field type, it is generally discouraged. Optional is primarily designed for use as a return type to indicate the possible absence of a value.
Conclusion
In this article, we learned about the Optional class in Java 8. The Optional class provides a way to handle the presence or absence of values, which reduces the risk of NullPointerExceptions. We discussed how we can declare Optional instances, with the help of various methods like isPresent(), get(), & ifPresent(), & saw a few examples of filtering, mapping, & chaining operations on Optional values.
You can also check out our other blogs on Code360.