Using Optional to Handle null in Java


Optional is a safer way to handle values that might be null.

Source Code

import java.util.Optional;

public class OptionalExample {
    public static void main(String[] args) {
        Optional empty = Optional.empty();
        Optional value = Optional.of("Hello");

        System.out.println(empty.isPresent()); // false
        System.out.println(value.isPresent()); // true
        System.out.println(value.get()); // Hello
    }
}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments