GregorianCalendar compareTo(GregorianCalendar) in Java

compareTo(GregorianCalendar): This method is available in java.util.GregorianCalendar class of Java.

Syntax:

int java.util.Calendar.compareTo(Calendar anotherCalendar)

This method takes one argument. This method compares the time values represented by two Calendar objects.

Parameters: One parameter is required for this method.

anotherCalendar: the Calendar to be compared.

Returns:

1. The value 0 if the time represented by the argument is equal to the time represented by this Calendar.

2. A value less than 0 if the time of this Calendar is before the time represented by the argument.

3. A value greater than 0 if the time of this Calendar is after the time represented by the argument.

Throws:

1. NullPointerException - if the specified Calendar is null.

2. IllegalArgumentException - if the time value of the specified Calendar object can't be obtained due to any invalid calendar values.

Approach 1: When no exceptions

Java

import java.util.GregorianCalendar;

public class GregorianCalendarcompareTo {
    public static void main(String[] args) {

        GregorianCalendar cal = new GregorianCalendar();
        GregorianCalendar anotherCalendar =
new GregorianCalendar();

        System.out.println(cal.compareTo(anotherCalendar));
    }
}

Output:

-1


Approach 2: NullPointerException 

Java

import java.util.GregorianCalendar;

public class GregorianCalendarcompareTo {
    public static void main(String[] args) {

        GregorianCalendar cal = new GregorianCalendar();
        GregorianCalendar anotherCalendar = null;

        System.out.println(cal.compareTo(anotherCalendar));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot read field "isTimeSet" because "calendar" is null at java.base/java.util.Calendar.getMillisOf(Calendar.java:3443) at java.base/java.util.Calendar.compareTo(Calendar.java:2820)


No comments:

Post a Comment