Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

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

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring