What is the OptionalLong.getAsLong() method in Java?

In Java, an OptionalLong object is a container object that may or may not contain a long value.

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

The getAsLong() method is used to get the long value present in an OptionalLong object. If the OptionalLong object doesn’t have a value, then NoSuchElementException is thrown.

Syntax

public long getAsLong()

This method doesn’t take any argument.

Code

The code below shows how to use the getAsLong() method.

import java.util.OptionalLong;
class OptionalLongGetExample {
public static void main(String[] args) {
OptionalLong optional = OptionalLong.of(1);
System.out.println("Value present in the optional object is: " + optional.getAsLong());
}
}

Explanation

In the code above:

  • In line 1, we imported the OptionalLong class.
import java.util.OptionalLong;
  • In line 5, we used the of() method to get an OptionalLong object with value 1.
OptionalLong optional = OptionalLong.of(1);
  • In line 6, we called the getAsLong() method on the object optional. The getAsLong() method will return the value present in optional.
optional.getAsLong(); // 1
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources