Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

optional
java
communitycreator

What is the Optional.get method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

RELATED TAGS

optional
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring