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 OptionalInt class is present in the java.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.

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 OptionalInt class.
import java.util.OptionalInt;
  • In line 5, we used the of() method to get an OptionalInt object with value 1.
OptionalInt optional = OptionalInt.of(1);
  • In line 6, we called the getAsInt() method on the object optional. The getAsInt() method will return the value present in optional.
optional.getAsInt(); // 1