What is the OptionalLong.orElse method in Java?

Overview

In Java, the OptionalLong object is a container object which may or may not contain a long value.

The OptionalLong class is present in the java.util package.

The orElse() method

The orElse method will return the long value present in the OptionalLong object. If the value is not present, then the passed argument is returned.

Syntax


public long orElse(long other)

Argument

The argument is the long value to be returned if the OptionalLong object is empty, which means there is no value present in the OptionalLong object.

Return value

If the OptionalLong object contains a long value, then the value is returned. Otherwise, the passed argument is returned.

Code

The code below denotes how to use the orElse method.

import java.util.OptionalLong;
class OptionalLongOrElseExample {
public static void main(String[] args) {
OptionalLong optional1 = OptionalLong.of(1);
System.out.println("Optional1 : " + optional1);
System.out.println("Long Value at Optional1 is : " + optional1.orElse(10));
OptionalLong optional2 = OptionalLong.empty();
System.out.println("\nOptional2 : " + optional2);
System.out.println("Long value at Optional2 is : " + optional2.orElse(3223232323l));
}
}

Explanation

In the code above:

  • Line 1: We imported the OptionalLong class.


    import java.util.OptionalLong;
    

  • Line 5: We created an OptionalLong object with the value 1 using the of method.


    OptionalLong optional1 = OptionalLong.of(1);
    

  • Line 7: We called the 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 
    

  • Line 9: We used the empty method to get an empty OptionalLong object. The returned object doesn’t have any value.


    OptionalLong optional2 = OptionalLong.empty();
    

  • Line 11: We called the orElse method on the optional2 object with 3223232323l as an argument. This method returns 3223232323 because the optional2 object doesn’t contain any value.


    optional2.orElse(3223232323l); //3223232323
    

Free Resources