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
OptionalIntobject is a container object which may or may not contain anintegervalue. TheOptionalIntclass is present in thejava.utilpackage.
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
OptionalIntclass.
import java.util.OptionalInt;
- In line 5, we use the
ofmethod to get anOptionalIntobject with the integer whose value is 1.
OptionalInt optional1 = OptionalInt.of(1);
optional1; // OptionalInt[1]
- In line 8, we use the
ofmethod to get anOptionalIntobject whose value is 100.
OptionalInt optional2 = OptionalInt.of(100);
optional2;// OptionalInt[100]