Optional empty() method in Java with examples

The empty() method of java.util.Optional class in Java is used to get an empty instance of this Optional class. This instance do not contain any value.

Syntax:

public static <T> 
  Optional<T> empty()

Parameters: This method accepts nothing.



Return value: This method returns an empty instance of this Optional class.

Below programs illustrate empty() method:
Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// Optional.empty() method
  
import java.util.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // create a Optional
        Optional<Integer> op
            = Optional.empty();
  
        // print value
        System.out.println("Optional: "
                           + op);
    }
}

chevron_right


Output:

Optional: Optional.empty

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// Optional.empty() method
  
import java.util.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // create a Optional
        Optional<String> op
            = Optional.empty();
  
        // print value
        System.out.println("Optional: "
                           + op);
    }
}

chevron_right


Output:

Optional: Optional.empty

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#empty–



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.