Java Language Optional

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

Optional is a container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Additional methods that depend on the presence of the contained value are provided, such as orElse(), which returns a default value if value not present, and ifPresent() which executes a block of code if the value is present.

Syntax

  • Optional.empty() // Creates an empty Optional instance.
  • Optional.of(value) // Returns an Optional with the specified non-null value. A NullPointerException will be thrown if the passed value is null.
  • Optional.ofNullable(value) // Returns an Optional with the specified value that may be null.


Got any Java Language Question?