equals()
is an instance method of the Duration
class that checks if two Duration
objects are equal. The comparison is based on the length of the durations.
This method is defined in the Duration
class, and the Duration
class is defined in the java.time
package.
Use the statement below to import the Duration
class.
import java.time.Duration;
public boolean equals(Object otherDuration)
Object otherDuration
: The duration object to check for equality.This method returns true
if the duration objects are equal. Otherwise, it returns false
.
In the code below, we use the equals()
method to compare two different Duration
objects and print the result to the console.
import java.time.Duration;public class Main{public static void main(String[] args) {// first duration object ofwith 15 hoursDuration duration1 = Duration.ofHours(15);// second duration object of 900 minutesDuration duration2 = Duration.ofMinutes(900);// We check the equality between the two duration objects using the equals methodSystem.out.printf("(%s == %s) = %s\n", duration1, duration2, duration1.equals(duration2));// modified second duration object of 5000 secondsduration2 = Duration.ofSeconds(5000);// We check the equality between the two duration objects using the equals methodSystem.out.printf("(%s == %s) = %s\n", duration1, duration2, duration1.equals(duration2));}}