</>

Technology

Core Java

Difficulty

Intermediate

Interview Question

What is the Optional class in Java 8 and how does it help?

Answer

Optional Class in Java 8

Optional<T> is a container object that may or may not contain a non-null value. It is designed to eliminate NullPointerException by making null-handling explicit.

Creating Optional

Java
// Empty Optional
Optional<String> empty = Optional.empty();

// Optional with value (throws NPE if value is null)
Optional<String> name = Optional.of("Alice");

// Optional that allows null (use this when value might be null)
Optional<String> nullable = Optional.ofNullable(getUserName());

Checking and Getting Value

Java
Optional<String> opt = Optional.ofNullable(getEmail());

// isPresent / isEmpty
if (opt.isPresent()) {
    System.out.println(opt.get()); // "alice@example.com"
}

// ifPresent — run action only if value exists
opt.ifPresent(email -> System.out.println("Sending to: " + email));

// orElse — default value if empty
String email = opt.orElse("default@example.com");

// orElseGet — use supplier for lazy default
String email2 = opt.orElseGet(() -> generateDefaultEmail());

// orElseThrow — throw exception if empty
String email3 = opt.orElseThrow(() -> new RuntimeException("Email not found"));

Transforming with map and flatMap

Java
Optional<String> upperEmail = Optional.ofNullable(getEmail())
    .map(String::toUpperCase)
    .filter(e -> e.contains("@"));

System.out.println(upperEmail.orElse("N/A"));

// Chained Optional — avoids nested null checks
// Before Optional (nested null checks):
String city = null;
if (user != null && user.getAddress() != null) {
    city = user.getAddress().getCity();
}

// With Optional:
String city = Optional.ofNullable(user)
    .map(User::getAddress)
    .map(Address::getCity)
    .orElse("Unknown");

Real-World Example

Java
// Without Optional — multiple null checks
public String getUserCity(int userId) {
    User user = userRepository.findById(userId);
    if (user == null) return "Unknown";
    Address address = user.getAddress();
    if (address == null) return "Unknown";
    return address.getCity() != null ? address.getCity() : "Unknown";
}

// With Optional — clean pipeline
public String getUserCity(int userId) {
    return userRepository.findOptionalById(userId)   // returns Optional<User>
        .map(User::getAddress)
        .map(Address::getCity)
        .orElse("Unknown");
}

In Automation Testing

Java
// Safe element lookup — return Optional instead of null
public Optional<WebElement> findOptional(By locator) {
    List<WebElement> elements = driver.findElements(locator);
    return elements.isEmpty() ? Optional.empty() : Optional.of(elements.get(0));
}

// Usage
findOptional(By.id("success-message"))
    .map(WebElement::getText)
    .ifPresent(msg -> assertTrue(msg.contains("Success")));

// Cookie retrieval
Optional.ofNullable(driver.manage().getCookieNamed("session_id"))
    .map(Cookie::getValue)
    .ifPresent(token -> setAuthToken(token));

Follow AutomateQA

Related Topics