What is the Optional.get method in Java?

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 the java.util package. Read more about the Optional class here.

Syntax

public T get()

Parameter

This method doesn’t take any parameters.

Return value

This method returns the value present in the Optional object. If no value is present, then NoSuchElementException is thrown.

Code

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());
}
}

Explanation

In the code above:

  • In line 1, we imported the Optional class.
import java.util.Optional;
  • In line 5, we used the of method to get an Optional object of the Integer type with value 1.
Optional<Integer> optional = Optional.of(1);
  • In line 6, we called the get method on the optional object. The get method will return the value present in the optional object.
optional.get();//1
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources