Monday, 16 June 2025

Most Commonly Java Interview Question in Java 8: What is Optional in Java 8?

 

Optional in Java 8:

In Java 8, Optional is a container object introduced in the java.util package. It is used to represent a value that can either be present (non-null) or absent (null). It provides a way to avoid NullPointerException (NPE) and improve code readability when dealing with nullable values.

Key Characteristics of Optional:

  1. Avoids Null Checks: Provides methods to handle nullable values without explicit null checks.
  2. Immutable: The Optional object is immutable, meaning its value cannot be changed once set.
  3. Improves Readability: It reduces boilerplate code and enhances readability when handling optional or nullable values.

Common Methods in Optional:

  1. Creating an Optional:
    • Optional.of(T value): Creates an Optional with a non-null value. Throws NullPointerException if the value is null.
    • Optional.ofNullable(T value): Creates an Optional that can hold a null or non-null value.
    • Optional.empty(): Returns an empty Optional.
  2. Checking for Value:
    • isPresent(): Returns true if a value is present, otherwise false.
    • isEmpty(): Returns true if no value is present, otherwise false.
  3. Retrieving the Value:
    • get(): Returns the value if present; otherwise, throws NoSuchElementException.
    • orElse(T other): Returns the value if present; otherwise, returns the provided default value.
    • orElseGet(Supplier<? extends T> supplier): Returns the value if present; otherwise, invokes the supplier and returns its result.
    • orElseThrow(Supplier<? extends X> exceptionSupplier): Returns the value if present; otherwise, throws an exception provided by the supplier.
  4. Processing the Value:
    • ifPresent(Consumer<? super T> action): Executes the given action if a value is present.
    • map(Function<? super T, ? extends U> mapper): Applies a mapping function if a value is present and returns a new Optional.
    • flatMap(Function<? super T, Optional<U>> mapper): Similar to map but avoids nested Optional.

Example Usage:

1.       Basic Usage

Optional<String> optional = Optional.ofNullable("Hello, World!");

 

if (optional.isPresent()) {

    System.out.println(optional.get()); // Output: Hello, World!

} else {

    System.out.println("No value present.");

}

2. Using orElse and ifPresent

Optional<String> optional = Optional.ofNullable(null);

 

// Using orElse

String result = optional.orElse("Default Value");

System.out.println(result); // Output: Default Value

 

// Using ifPresent

optional.ifPresent(value -> System.out.println("Value: " + value)); // Does nothing

 

3.      Using map and flatMap

Optional<String> optional = Optional.of("Hello");

 

Optional<Integer> lengthOptional = optional.map(String::length);

lengthOptional.ifPresent(System.out::println); // Output: 5

 

Benefits of Optional:

  1. Eliminates the risk of NullPointerException.
  2. Promotes functional programming by using methods like map, flatMap, and ifPresent.
  3. Makes the code more expressive and easier to understand.

 

No comments:

Post a Comment