Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

optionalint
ispresent
java
communitycreator

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

Answers Code

Overview

In Java, the OptionalInt object is a container object which may or may not contain an integer value.

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

The isPresent() method

The isPresent() method is used to check if the OptionalInt object contains a value.

Syntax


public boolean isPresent()

Arguments

This method doesn’t take an argument.

Return value

This method returns true if the OptionalInt object contains a integer value. Otherwise, false will be returned.

Code

The code below denotes how to use the isPresent method.

import java.util.OptionalInt;
class OptionalIntIsPresentExample {
public static void main(String[] args) {
OptionalInt optional1 = OptionalInt.empty();
OptionalInt optional2 = OptionalInt.of(1);
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:

  • Line 1: We imported the OptionalInt class.


    import java.util.OptionalInt;
    

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


    OptionalInt optional1 = OptionalInt.empty();
    

  • Line 6: We used the of method to get an OptionalInt object with value 1.


    OptionalInt optional2 = OptionalInt.of(1);
    

  • Line 7: We called the isPresent method on the optional1 object. This object doesn’t have any value, so false will be returned.


    optional1.isPresent();//false
    

  • Line 8: We called the isPresent method on the optional2 object. This object has 1 as the value, so true will be returned.


    optional2.isPresent();//true
    

RELATED TAGS

optionalint
ispresent
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.

Answers Code
Keep Exploring