- 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
Instant compareTo() method in Java
Two Instant objects can be compared using the compareTo() method in the Instant class in Java. This method requires a single parameter i.e. the Instant object to be compared.
If the first Instant object is greater than the second Instant object it returns a positive number, if the first Instant object is lesser than the second Instant object it returns a negative number and if both the Instant objects are equal it returns zero.
A program that demonstrates this is given as follows
Example
import java.time.*; public class Demo { public static void main(String[] args) { Instant i1 = Instant.parse("2019-01-13T18:35:19.00Z"); Instant i2 = Instant.parse("2019-01-13T16:10:35.00Z"); System.out.println("The first Instant object is: " + i1); System.out.println("The second Instant object is: " + i2); int val = i1.compareTo(i2); if(val > 0) System.out.println("
The first Instant object is greater than the second Instant object"); else if(val < 0) System.out.println("
The first Instant object is lesser than the second Instant object"); else System.out.println("
The Instant objects are equal"); } }
Output
The first Instant object is: 2019-01-13T18:35:19Z The second Instant object is: 2019-01-13T16:10:35Z The first Instant object is greater than the second Instant object
Now let us understand the above program.
First the two Instant 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:
Instant i1 = Instant.parse("2019-01-13T18:35:19.00Z"); Instant i2 = Instant.parse("2019-01-13T16:10:35.00Z"); System.out.println("The first Instant object is: " + i1); System.out.println("The second Instant object is: " + i2); int val = i1.compareTo(i2); if(val > 0) System.out.println("
The first Instant object is greater than the second Instant object"); else if(val < 0) System.out.println("
The first Instant object is lesser than the second Instant object"); else System.out.println("
The Instant objects are equal");
Advertisements