What is the OptionalInt.of method in Java?

The of method gets an instance of the Optional class with the specified integer value.

In Java, the OptionalInt object is a container object which may or may not contain an integer value. The OptionalInt class is present in the java.util package.

Syntax

public static OptionalInt of(int value)

Parameter

The int value to be present in the OptionalInt object.

Return value

This method returns an OptionalInt object with the specified integer value.

Code

The code below denotes how the of method is used:

import java.util.OptionalInt;
class OptionalIntOfExample {
public static void main(String[] args) {
OptionalInt optional1 = OptionalInt.of(1);
System.out.println("Optional 1: " + optional1);
OptionalInt optional2 = OptionalInt.of(100);
System.out.println("Optional 2: " + optional2);
}
}

Explanation

  • In line 1, we import the OptionalInt class.
import java.util.OptionalInt;
  • In line 5, we use the of method to get an OptionalInt object with the integer whose value is 1.
OptionalInt optional1 = OptionalInt.of(1);
optional1; // OptionalInt[1]
  • In line 8, we use the of method to get an OptionalInt object whose value is 100.
OptionalInt optional2 = OptionalInt.of(100);
optional2;// OptionalInt[100]

Free Resources