In Java, an OptionalInt
object is a container object that may or may not contain an integer value.
The
OptionalInt
class is present in thejava.util
package.
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.
public int getAsInt()
This method doesn’t take any arguments.
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());}}
In the code above:
OptionalInt
class.import java.util.OptionalInt;
of()
method to get an OptionalInt
object with value 1
.OptionalInt optional = OptionalInt.of(1);
getAsInt()
method on the object optional
. The getAsInt()
method will return the value present in optional
.optional.getAsInt(); // 1