Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is Optional in Java and how does it help avoid NullPointerException? Java में Optional क्या है और NullPointerException से बचने में कैसे मदद करता है?

Answer

Optional<T> is a container object that may or may not hold a non-null value, forcing callers to explicitly handle the 'no value' case instead of accidentally dereferencing null.

import java.util.Optional;

// WITHOUT Optional - null checks scattered everywhere, easy to forget
public User findUserById(int id) {
    return null;  // caller might forget to check for null
}
User user = findUserById(5);
// user.getName();  // NullPointerException if findUserById returned null

// WITH Optional - the return type itself signals 'might be absent'
public Optional<User> findUserByIdSafe(int id) {
    User user = database.lookup(id);
    return Optional.ofNullable(user);  // wraps null safely
}

Optional<User> result = findUserByIdSafe(5);

// Checking presence explicitly
if (result.isPresent()) {
    System.out.println(result.get().getName());
}

// Better: functional-style handling, no explicit null checks needed
result.ifPresent(u -> System.out.println(u.getName()));

String name = result.map(User::getName).orElse('Unknown');

User defaultUser = result.orElseGet(() -> new User('Guest'));

User required = result.orElseThrow(() -> new RuntimeException('User not found'));

// Chaining operations safely
Optional<String> upperName = result
    .map(User::getName)
    .filter(n -> !n.isEmpty())
    .map(String::toUpperCase);

// Creating Optionals
Optional<String> empty = Optional.empty();
Optional<String> present = Optional.of('Hello');  // throws if value is null
Optional<String> maybeNull = Optional.ofNullable(possiblyNullValue);

// Anti-pattern: don't just call .get() without checking - defeats the purpose
// String bad = result.get();  // still throws NoSuchElementException if empty!

Optional<T> एक container object है जो non-null value रख सकता है या नहीं, callers को 'no value' case explicitly handle करने पर मजबूर करता है।

import java.util.Optional;

public User findUserById(int id) {
    return null;  // caller भूल सकता है check करना
}
User user = findUserById(5);
// user.getName();  // NullPointerException

public Optional<User> findUserByIdSafe(int id) {
    User user = database.lookup(id);
    return Optional.ofNullable(user);
}

Optional<User> result = findUserByIdSafe(5);

if (result.isPresent()) {
    System.out.println(result.get().getName());
}

result.ifPresent(u -> System.out.println(u.getName()));

String name = result.map(User::getName).orElse('Unknown');

User defaultUser = result.orElseGet(() -> new User('Guest'));

User required = result.orElseThrow(() -> new RuntimeException('User not मिला'));

Optional<String> upperName = result
    .map(User::getName)
    .filter(n -> !n.isEmpty())
    .map(String::toUpperCase);

Optional<String> empty = Optional.empty();
Optional<String> present = Optional.of('Hello');
Optional<String> maybeNull = Optional.ofNullable(possiblyNullValue);

Was this answer clear?