What is the OptionalInt.getAsInt() method in Java?
In Java, an OptionalInt object is a container object that may or may not contain an integer value.
The
OptionalIntclass is present in thejava.utilpackage.
The getAsInt() method is used to get the integer value present in an OptionalInt object. If the OptionalInt object doesn’t have a value, then NoSuchElementException is thrown.
Syntax
public int getAsInt()
This method doesn’t take any arguments.
Code
The code below shows how to use the getAsInt() method.
import java.util.OptionalInt;class OptionalIntGetExample {public static void main(String[] args) {OptionalInt optional = OptionalInt.of(1);System.out.println("Int value present in the optional object is: " + optional.getAsInt());}}
Explanation
In the code above:
- In line 1, we imported the
OptionalIntclass.
import java.util.OptionalInt;
- In line 5, we used the
of()method to get anOptionalIntobject with value1.
OptionalInt optional = OptionalInt.of(1);
- In line 6, we called the
getAsInt()method on the objectoptional. ThegetAsInt()method will return the value present inoptional.
optional.getAsInt(); // 1