Optional hashCode() method in Java with examples

Last Updated : 9 Sep, 2026

The hashCode() method of the java.util.Optional class returns the hash code of the value contained in the Optional. If the Optional is empty, the method returns 0.

  • The method does not accept any parameters.
  • hashCode() returns an int value.
  • The method does not throw an exception.

Examples:

Input: Optional = Optional[456]
Output: Optional hashCode value: 456

Input: Optional = Optional.empty
Output: Optional hashCode value: 0

Syntax:

public int hashCode()

Methods to Use hashCode()

The hashCode() method provides a numeric hash value for an object and helps represent the object in hash-based collections. The following examples demonstrate its use with present and empty Optional objects.

1. Using hashCode() with a Present Value

The following program creates an Optional containing the integer 456 and retrieves its hash code using hashCode().

Java
import java.util.*;

public class OptionalDemo {
    public static void main(String[] args)
    {

        Optional<Integer> op = Optional.of(456);

        System.out.println("Optional: " + op);

        System.out.println("Optional hashCode value: "+ op.hashCode());
    }
}

Output
Optional: Optional[456]
Optional hashCode value: 456

Explanation: The Optional contains the value 456, whose hash code is 456. Therefore, hashCode() returns 456.

2. Using hashCode() with an Empty Optional

The following program creates an empty Optional and retrieves its hash code.

Java
import java.util.*;

public class OptionalDemo {
    public static void main(String[] args) {

        Optional<Integer> op = Optional.empty();

        System.out.println("Optional: " + op);

        System.out.println("Optional hashCode value: "
                + op.hashCode());
    }
}

Output
Optional: Optional.empty
Optional hashCode value: 0

Explanation: The Optional does not contain a value, so hashCode() returns 0. The method does not throw an exception for an empty Optional.

Comment