In Java, the OptionalInt
object is a container object that may or may not contain an integer
value.
The
OptionalInt
class is present in thejava.util
package.
orElse
methodThe orElse
method will return the integer
value present in the OptionalInt
object. If the value is not present, then the passed argument is returned.
public int orElse(int other)
The input parameter is the integer
value to be returned if the OptionalInt
object is OptionalInt
object
If the OptionalInt
object contains an int
value, then the value is returned. Otherwise, the passed argument is returned.
The code below shows how to use the orElse
method.
import java.util.OptionalInt;class OptionalIntOrElseExample {public static void main(String[] args) {OptionalInt optional1 = OptionalInt.of(1);System.out.println("Optional1 : " + optional1);System.out.println("Integer Value at Optional1 is : " + optional1.orElse(10));OptionalInt optional2 = OptionalInt.empty();System.out.println("\nOptional2 : " + optional2);System.out.println("Integer value at Optional2 is : " + optional2.orElse(100));}}
In the code above:
OptionalInt
class.import java.util.OptionalInt;
OptionalInt
object with the integer
value 1
using the of
method.OptionalInt optional1 = OptionalInt.of(1);
orElse
method on the optional1
object with 10
as an argument. This method returns 1
because the optional1
object contains the value.optional1.orElse(10); // 1
empty
method to get an empty OptionalInt
object. The returned object doesn’t have any value.OptionalInt optional2 = OptionalInt.empty();
orElse
method on the optional2
object with 100
as an argument. This method returns 100
because the optional2
object does not contain any value.optional2.orElse(100); //100