Optional <?>
Before Java 8, dealing with null values often led to error-prone code. Developers had to manually check for nulls
To address these issues, Java 8 introduced the optional class, inspired by functional programming languages. It encapsulates a value that can be present or absent, allowing developers to handle optional values
What is Optional?
optional is a container object used to represent the presence or absence of a value. It is essentially a wrapper around an object that might be null.
Optional<String> optional = Optional.of("Hello");
//Optional.of(T value): Creates an Optional with a non-null value.
//cannot pass null here it will give NullPointerException
Optional<String> emptyOptional = Optional.empty();
//Optional.empty(): Creates an empty Optional.
Optional<String> nullableOptional = Optional.ofNullable(null);
//Optional.ofNullable(T value): Creates an Optional
//that can hold a null value.
Common Methods in Optional
isPresent()
if (optional.isPresent()) {
System.out.println("Value is present");
}
/**
* If a value is present, returns {@code true}, otherwise {@code false}.
*
* @return {@code true} if a value is present, otherwise {@code false}
*/
public boolean isPresent() {
return value != null;
}isEmpty()
/**
* If a value is not present, returns {@code true}, otherwise
* {@code false}.
*
* @return {@code true} if a value is not present, otherwise {@code false}
* @since 11
*/
public boolean isEmpty() {
return value == null;
}ifPresent()
optional.ifPresent(value -> System.out.println("Value: " + value));
/**
* If a value is present, performs the given action with the value,
* otherwise does nothing.
*
* @param action the action to be performed, if a value is present
* @throws NullPointerException if value is present and the given action is
* {@code null}
*/
public void ifPresent(Consumer<? super T> action) {
if (value != null) {
action.accept(value);
}
}orElse()
String value = optional.orElse("Default Value");Get sunimal malkakulageβs stories inΒ yourΒ inbox
Join Medium for free to get updates fromΒ thisΒ writer.
/**
* If a value is present, returns the value, otherwise returns
* {@code other}.
*
* @param other the value to be returned, if no value is present.
* May be {@code null}.
* @return the value, if present, otherwise {@code other}
*/
public T orElse(T other) {
return value != null ? value : other;
}
orElseGet()
String value = optional.orElseGet(() -> "Default Value");
/**
* If a value is present, returns the value, otherwise returns the result
* produced by the supplying function.
*
* @param supplier the supplying function that produces a value to be returned
* @return the value, if present, otherwise the result produced by the
* supplying function
* @throws NullPointerException if no value is present and the supplying
* function is {@code null}
*/
public T orElseGet(Supplier<? extends T> supplier) {
return value != null ? value : supplier.get();
}orElseThrow()
String value = optional.orElseThrow(() -> new IllegalArgumentException("Value not present"));
/**
* If a value is present, returns the value, otherwise throws
* {@code NoSuchElementException}.
*
* @return the non-{@code null} value described by this {@code Optional}
* @throws NoSuchElementException if no value is present
* @since 10
*/
public T orElseThrow() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}When to Use Optional
- Method Return Types: Use
Optionalto clearly indicate that a method might not return a value. This helps make the code more explicit and safer.
When to Avoid Optional
- Fields: Avoid using optional for class fields as it can introduce unnecessary complexity and overhead.
- Method Parameters: Do not use optional in method parameters. Instead, use traditional null checks or other patterns.
- Collections: Refrain from using optional within collections. It can lead to overcomplicated and less efficient code.
Performance Considerations
- While optional can introduce some performance overhead, its benefits in improving code readability and reducing the risk of NullPointerException.
Readability and Maintainability
- Using optional helps make your code more readable and maintainable by clearly showing when a value might be absent. This reduces the chances of runtime errors and makes the code easier to understand and manage.

![Ja[Var]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*YGQhwqCH9F-jVwbLwjgA9g.png)







