Duration equals() method in Java

Java 8ProgrammingObject Oriented Programming

The equality of two durations can be determined using the equals() method in the Duration class in Java. This method requires a single parameter i.e. the duration to be compared. Also, it returns true if both the durations are equal and false otherwise.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.Duration;
public class GFG {
   public static void main(String[] args) {
      Duration d1 = Duration.ofDays(1);
      Duration d2 = Duration.ofHours(24);
      boolean flag = d1.equals(d2);
      if(flag)
         System.out.println("The durations are equal");
      else
         System.out.println("The durations are not equal");
   }
}

Output

The durations are equal

Now let us understand the above program.

The two durations are compared using the method equals() and the returned value is stored in the flag. Then it is displayed whether the durations are equal or not. A code snippet that demonstrates this is as follows −

Duration d1 = Duration.ofDays(1);
Duration d2 = Duration.ofHours(24);
boolean flag = d1.equals(d2);
if(flag)
   System.out.println("The durations are equal");
else
   System.out.println("The durations are not equal");
raja
Published on 13-Mar-2019 11:23:04
Advertisements