Duration compareTo() method in Java

Java 8Object Oriented ProgrammingProgramming

Two durations can be compared using the compareTo() method in the Duration class in Java. This method requires a single parameter i.e. the duration to be compared.

If the first duration is greater than the second duration it returns a positive number, if the first duration is lesser than the second duration it returns a negative number and if both the durations are equal it returns zero.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.Duration;
public class Demo {
   public static void main(String[] args) {
      Duration d1 = Duration.ofHours(8);
      Duration d2 = Duration.ofHours(6);
      System.out.println("The first duration is: " + d1);
      System.out.println("The second duration is: " + d2);
      int val = d1.compareTo(d2);
      if(val > 0)
         System.out.println("\nThe first duration is greater than the second duration");
      else if(val < 0)
         System.out.println("\nThe first duration is lesser than the second duration");
      else
         System.out.println("\nThe durations are equal");
   }
}

Output

The first duration is: PT8H
The second duration is: PT6H
The first duration is greater than the second duration

Now let us understand the above program.

First the two durations are displayed. Then the durations are compared using the compareTo() method and the result is displayed using if else statement. A code snippet that demonstrates this is as follows −

Duration d1 = Duration.ofHours(8);
Duration d2 = Duration.ofHours(6);
System.out.println("The first duration is: " + d1);
System.out.println("The second duration is: " + d2);
int val = d1.compareTo(d2);
if(val > 0)
   System.out.println("\nThe first duration is greater than the second duration");
else if(val < 0)
   System.out.println("\nThe first duration is lesser than the second duration");
else
   System.out.println("\nThe durations are equal");
raja
Published on 26-Mar-2019 05:06:43
Advertisements