Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the OptionalDouble.getAsDouble 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.

The getAsDouble method is used to get the double value of the OptionalDouble object. If the OptionalDouble object doesn’t have a value, then NoSuchElementException is thrown.

In Java, the OptionalDouble object is a container object that may or may not contain a double value. The OptionalDouble class is present in the java.util package.

Syntax

public double getAsDouble()

Parameters

This method doesn’t take any parameters.

Return value

The getAsDouble method returns the double value present in the OptionalDouble object. If no value is present, then NoSuchElementException is thrown.

Code

The code below denotes how to use the getAsDouble method.

import java.util.OptionalDouble;
class OptionalDoubleGetExample {
public static void main(String[] args) {
OptionalDouble optional = OptionalDouble.of(1.5);
System.out.println("Dobule value present in the optional object is: " + optional.getAsDouble());
}
}

Explanation

In the code above:

  • In line 1, we import the OptionalDouble class.
import java.util.OptionalDouble;
  • In line 5, we use the of method to get an OptionalDouble object with double value 1.5.
OptionalDouble optional = OptionalDouble.of(1.5);
  • In line 6, we call the getAsDouble method on the optional object. The getAsDouble method will return the double value present in the optional object.
optional.getAsDouble();// 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