Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the OptionalDouble.isPresent() 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 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.

The isPresent() method is used to check if an OptionalDouble object contains a value.

Syntax

public boolean isPresent()

Argument

This method doesn’t take any argument.

Return value

This method returns true if the OptionalDouble object contains a double value. Otherwise, it returns false.

Code

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

import java.util.OptionalDouble;
class OptionalDoubleIsPresentExample {
public static void main(String[] args) {
OptionalDouble optional1 = OptionalDouble.empty();
OptionalDouble optional2 = OptionalDouble.of(1.5);
System.out.println("Checking if optional1 has value : " + optional1.isPresent());
System.out.println("Checking if optional2 has value : " + optional2.isPresent());
}
}

Explanation

In the code above:

  • In line 1, we imported the OptionalDouble class.
import java.util.OptionalDouble;
  • In line 5, we used the empty() method to get an empty OptionalDouble object. The returned object doesn’t have any value.
OptionalDouble optional1 = OptionalDouble.empty();
  • In line 6, we used the of() method to get an OptionalDouble object with value 1.5.
OptionalDouble optional2 = OptionalDouble.of(1.5);
  • In line 7, we called the isPresent() method on the object optional1. This object doesn’t have any value, so false is returned.
optional1.isPresent(); //false
  • In line 8, we called the isPresent() method on the object optional2. This object has 1.5 as the value, so true is returned.
optional2.isPresent(); //true

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