LocalTime compareTo() method in Java

Java 8Object Oriented ProgrammingProgramming

Two LocalTime objects can be compared using the compareTo() method in the LocalTime class in Java. This method requires a single parameter i.e. the LocalTime object to be compared.

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

A program that demonstrates this is given as follows

Example

 Live Demo

import java.time.*;
public class Main{
   public static void main(String[] args){
      LocalTime lt1 = LocalTime.parse("11:37:12");
      LocalTime lt2 = LocalTime.parse("23:15:30");
      System.out.println("The first LocalTime object is: " + lt1);
      System.out.println("The second LocalTime object is: " + lt2);
      int val = lt1.compareTo(lt2);
      if(val > 0)
         System.out.println("\nThe first LocalTime object is greater than the second LocalTimeobject");
      else if(val < 0)
         System.out.println("\nThe first LocalTime object is lesser than the second LocalTimeobject");
      else
         System.out.println("\nThe LocalTime objects are equal");
   }
}

output

The first LocalTime object is: 11:37:12
The second LocalTime object is: 23:15:30
The first LocalTime object is lesser than the second LocalTime object

Now let us understand the above program.

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

LocalTime lt1 = LocalTime.parse("11:37:12");
LocalTime lt2 = LocalTime.parse("23:15:30");

System.out.println("The first LocalTime object is: " + lt1);
System.out.println("The second LocalTime object is: " + lt2);
int val = lt1.compareTo(lt2);

if(val > 0)
   System.out.println("\nThe first LocalTime object is greater than the second LocalTimeobject");
else if(val < 0)
   System.out.println("\nThe first LocalTime object is lesser than the second LocalTimeobject");
else
System.out.println("\nThe LocalTime objects are equal");
raja
Published on 26-Mar-2019 08:12:37
Advertisements