What is Duration.equals() in Java?

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;

Syntax


public boolean equals(Object otherDuration)

Parameters

  • Object otherDuration: The duration object to check for equality.

Return value

This method returns true if the duration objects are equal. Otherwise, it returns false.

Code

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 hours
Duration duration1 = Duration.ofHours(15);
// second duration object of 900 minutes
Duration duration2 = Duration.ofMinutes(900);
// We check the equality between the two duration objects using the equals method
System.out.printf("(%s == %s) = %s\n", duration1, duration2, duration1.equals(duration2));
// modified second duration object of 5000 seconds
duration2 = Duration.ofSeconds(5000);
// We check the equality between the two duration objects using the equals method
System.out.printf("(%s == %s) = %s\n", duration1, duration2, duration1.equals(duration2));
}
}