๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Optional Class  


Introduction
  • The Optional class in Java is a container object that may or may not contain a non-null value.
  • Introduced in Java 8 to avoid NullPointerException and provide a more functional approach to handling null values.
  • It is part of the java.util package.
  • An Optional can either contain a value (non-empty) or be empty.
  • Using Optional encourages better null-checking and cleaner code.
  • Uses of Optional Class:
    • To avoid NullPointerException by explicitly handling the presence or absence of a value.
    • To provide clearer and more readable code for null-checks.
    • To use functional-style methods like map(), filter() and ifPresent() for handling optional values.
Syntax and Important Methods
  • Creating Optional objects:
    // Creating an empty Optional
    Optional emptyOpt = Optional.empty();
    
    // Creating an Optional with a non-null value
    Optional valueOpt = Optional.of("Java 8");
    
    // Creating an Optional that may contain null
    Optional nullableOpt = Optional.ofNullable(getValue());
  • Important Methods of Optional:
    • isPresent() - Returns true if value is present.
    • ifPresent(Consumer action) - Executes action if value is present.
    • orElse(T other) - Returns value if present, otherwise returns other.
    • orElseGet(Supplier other) - Returns value if present, otherwise invokes Supplier and returns its result.
    • orElseThrow() - Returns value if present, otherwise throws NoSuchElementException.
    • map(Function mapper) - Applies function if value is present and returns Optional of result.
    • filter(Predicate predicate) - Returns Optional if value matches predicate, otherwise empty Optional.
Program:
  • Below is the program demonstrating Optional class in Java:
    import java.util.Optional;
    
    public class MainAppOptional
    {
        public static void main(String[] args)
        {
            // Creating an Optional with a non-null value
            Optional nameOpt = Optional.of("Deepak");
    
            // Checking if value is present
            if(nameOpt.isPresent()) {
                System.out.println("Value is present: " + nameOpt.get());
            }
    
            // Using ifPresent()
            nameOpt.ifPresent(name -> System.out.println("Hello, " + name));
    
            // Optional with null value
            Optional emptyOpt = Optional.ofNullable(null);
    
            // Using orElse()
            String defaultName = emptyOpt.orElse("Default Name");
            System.out.println("Value: " + defaultName);
    
            // Using map() and filter()
            Optional result = nameOpt
                    .filter(name -> name.startsWith("D"))
                    .map(name -> name.toUpperCase());
    
            result.ifPresent(System.out::println);
        }
    }