The get
method is used to get the value of the Optional
object. If the Optional
object doesn’t have a value, then NoSuchElementException
is thrown.
In Java, the Optional
object is a container object which may or may not contain a value. We can replace the multiple null
checks using the Optional
object’s isPresent
method.
The
Optional
class is present in thejava.util
package. Read more about theOptional
class here.
public T get()
This method doesn’t take any parameters.
This method returns the value present in the Optional
object. If no value is present, then NoSuchElementException
is thrown.
The below code denotes how to use the get
method.
import java.util.Optional;class OptionalGetExample {public static void main(String[] args) {Optional<Integer> optional = Optional.of(1);System.out.println("Value present in the optional object is: " + optional.get());}}
In the code above:
Optional
class.import java.util.Optional;
of
method to get an Optional
object of the Integer
type with value 1
.Optional<Integer> optional = Optional.of(1);
get
method on the optional
object. The get
method will return the value present in the optional
object.optional.get();//1