In Java 8 and later versions, the Optional class is part of the java.util package and provides a way to handle null values in an effective way and helps to avoid NullPointerExceptions. The Optional class lets you put a value that might be empty or null inside it. This helps you do things safely without needing to directly check if the value is null. Let’s learn today how you can use the Optional class to handle null values: How to use the Optional class in Java 8 to handle null values

How to use the Optional class in Java 8 to handle null values? Share on X

  1. Create an Optional instance:
    • To create an Optional instance with a non-null value, you can use Optional.of(value).
    • To create an Optional instance with a nullable value, you can use Optional.ofNullable(value).
    • To create an empty Optional, you can use Optional.empty().
  2. Access the value inside an Optional:
    • You can use the get() method to retrieve the value from an Optional. But, be careful when using this method, because it may throw a NoSuchElementException if the Optional is empty.
  3. Check if the Optional has a value:
    • You can use the isPresent() method to check if the Optional contains a value.
    • On the other hand, you can also use the ifPresent(Consumer<T> consumer) method to perform an action on the value if it is present.
  4. Handle the missing value:
    • You can use the orElse(T other) method to provide a default value if the Optional is empty.
    • You can use the orElseGet(Supplier<? extends T> supplier) method to supply a default value using a Supplier if the Optional is empty.

Here’s an example on the usage of Optional:

 

Output:

find first non repeated character in a string using Java 8

By using the Optional class, one can surely make the code more robust and less prone to NullPointerExceptions, as it encourages us to handle the presence or absence of values explicitly. 

 

Use of Optional() class in Java 8..!!! Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    http://Techndeck.com deepak.rkgit@gmail.com Verma Deepak