Home »
Java »
Java Reference »
Java Instant Class
Java Instant Class | compareTo() Method with Example
Instant Class compareTo() method: Here, we are going to learn about the compareTo() method of Instant Class with its syntax and example.
Submitted by Preeti Jain, on May 21, 2020
Instant Class compareTo() method
- compareTo() method is available in java.time package.
- compareTo() method is used to compare this Instant object to the given object.
- compareTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- compareTo() method may throw an exception at the time of comparing.
NullPointerException: This exception may throw when the given parameter is null exists.
Syntax:
public int compareTo(Instant ins);
Parameter(s):
- Instant ins – represents the object to be compared to this Instant.
Return value:
The return type of this method is int, it may return anyone of the given values,
- If (this Instant) < (Instant ins), it returns -1.
- If (this Instant) > (Instant ins), it returns 1.
- If (this Instant) == (Instant ins), it returns 0.
Example:
// Java program to demonstrate the example
// of int compareTo() method of Instant
import java.time.*;
public class CompareOfInstant {
public static void main(String args[]) {
// Instantiates two Instant
Instant ins1 = Instant.parse("2006-04-03T05:10:15.00Z");
Instant ins2 = Instant.parse("2007-06-05T10:20:30.00Z");
// Display ins1,ins2
System.out.println("Instant ins1 and ins2: ");
System.out.println("ins1: " + ins1);
System.out.println("ins2: " + ins2);
System.out.println();
// Here, this method compares this Instant
// (ins1) to the given Instant(ins2) i.e.
// here it returns -1 because ins1 < ins2
int compare = ins1.compareTo(ins2);
// Display compare
System.out.println("ins1.compareTo(ins2): " + compare);
// Here, this method compares this Instant
// (ins1) to the given Instant(ins1) i.e.
// here it returns 0 because ins1 == ins1
compare = ins1.compareTo(ins1);
// Display compare
System.out.println("ins1.compareTo(ins1): " + compare);
// Here, this method compares this Instant
// (ins2) to the given Instant(ins1) i.e.
// here it returns 1 because ins1 > ins2
compare = ins2.compareTo(ins1);
// Display compare
System.out.println("ins2.compareTo(ins1): " + compare);
}
}
Output
Instant ins1 and ins2:
ins1: 2006-04-03T05:10:15Z
ins2: 2007-06-05T10:20:30Z
ins1.compareTo(ins2): -1
ins1.compareTo(ins1): 0
ins2.compareTo(ins1): 1