Last Updated : 12 Jul, 2025
The equals() method of
java.util.Optional classin Java is used to check for equality of this Optional with the specified Optional. This method takes an Optional instance and compares it with this Optional and returns a boolean value representing the same.
Syntax:public boolean equals(Object obj)Parameter:
This method accepts a parameter
objwhich is the Optional to be checked for equality with this Optional.
Return Value:This method returns a
booleanwhich tells if this Optional is equal to the specified Object.
Exception:This method do not throw any Exception.
Program 1: Java
// Java program to demonstrate
// the above method
import java.text.*;
import java.util.*;
public class OptionalDemo {
public static void main(String[] args)
{
Optional<Integer> op1
= Optional.of(456);
System.out.println("Optional 1: "
+ op1);
Optional<Integer> op2
= Optional.of(456);
System.out.println("Optional 2: "
+ op2);
System.out.println("Comparing Optional 1"
+ " and Optional 2: "
+ op1.equals(op2));
}
}
Output:
Optional 1: Optional[456] Optional 2: Optional[456] Comparing Optional 1 and Optional 2: trueProgram 2: Java
// Java program to demonstrate
// the above method
import java.text.*;
import java.util.*;
public class OptionalDemo {
public static void main(String[] args)
{
Optional<Integer> op1
= Optional.of(456);
System.out.println("Optional 1: "
+ op1);
Optional<Integer> op2
= Optional.empty();
System.out.println("Optional 2: "
+ op2);
System.out.println("Comparing Optional 1"
+ " and Optional 2: "
+ op1.equals(op2));
}
}
Output:
Optional 1: Optional[456] Optional 2: Optional.empty Comparing Optional 1 and Optional 2: falseReference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#equals-java.lang.Object-
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4