The compareTo(ZoneOffset) method of ZoneOffset Class in java.time package is used to compare another instance of ZoneOffset passed as the parameter to this ZoneOffset instance. This method returns an integer value which is the comparator value.
Syntax:
public int compareTo(ZoneOffset anotherZoneOffset)
Parameters: This method accepts accepts a parameter anotherZoneOffset which is to be compared to this ZoneOffset instance.
Return Value: This method returns an integer value as follows:
- if this instance is greater than instance passed as a parameter, then a positive value is returned
- if this instance is equal to the instance passed as a parameter, then a zero (0) is returned
- if this instance is less than instance passed as a parameter then a negative value is returned.
Exceptions: This method throws NullPointerException if anotherZoneOffset passed as parameter is null.
Below examples illustrate the ZoneOffset.compareTo() method:
Example 1:
// Java code to illustrate compareTo() method import java.time.*; public class GFG { public static void main(String[] args) { // Get the ZoneOffset instance ZoneOffset zoneOffset1 = ZoneOffset.ofHours( 5 ); System.out.println( "ZoneOffset 1: " + zoneOffset1); // Get the ZoneOffset instance ZoneOffset zoneOffset2 = ZoneOffset.ofHours( 5 ); System.out.println( "ZoneOffset 2: " + zoneOffset2); // Get the ZoneOffset instance ZoneOffset zoneOffset3 = ZoneOffset.ofHours( 3 ); System.out.println( "ZoneOffset 3: " + zoneOffset3); // Using compareTo() method System.out.println( "ZoneOffset 1 " + "compared to ZoneOffset 2: " + zoneOffset1.compareTo(zoneOffset2)); // Using compareTo() method System.out.println( "ZoneOffset 1 " + "compared to ZoneOffset 3: " + zoneOffset1.compareTo(zoneOffset3)); // Using compareTo() method System.out.println( "ZoneOffset 3 " + "compared to ZoneOffset 1: " + zoneOffset3.compareTo(zoneOffset1)); } } |
ZoneOffset 1: +05:00 ZoneOffset 2: +05:00 ZoneOffset 3: +03:00 ZoneOffset 1 compared to ZoneOffset 2: 0 ZoneOffset 1 compared to ZoneOffset 3: -7200 ZoneOffset 3 compared to ZoneOffset 1: 7200
Example 2: To show NullPointerException
// Java code to illustrate compareTo() method import java.time.*; public class GFG { public static void main(String[] args) { try { // Get the ZoneOffset instance ZoneOffset zoneOffset = ZoneOffset.ofHours( 3 ); System.out.println( "ZoneOffset: " + zoneOffset); // Using compareTo() method System.out.println( "ZoneOffset " + "compared to null: " ); zoneOffset.compareTo( null ); } catch (Exception e) { System.out.println(e); } } } |
ZoneOffset: +03:00 ZoneOffset compared to null: java.lang.NullPointerException
Reference: Oracle Doc