Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the OptionalInt.getAsInt() 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.

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

RELATED TAGS

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