- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
LocalTime compareTo() method in Java
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
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("
The first LocalTime object is greater than the second LocalTimeobject"); else if(val < 0) System.out.println("
The first LocalTime object is lesser than the second LocalTimeobject"); else System.out.println("
The 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("
The first LocalTime object is greater than the second LocalTimeobject"); else if(val < 0) System.out.println("
The first LocalTime object is lesser than the second LocalTimeobject"); else System.out.println("
The LocalTime objects are equal");
Advertisements