Calendar compareTo(Calendar) in Java

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

Syntax:

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

This method takes one argument of type Calendar as its parameter. 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 exception

Java

import java.util.Calendar;

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

        // create a calendar
        Calendar calendar = Calendar.getInstance();
        Calendar anotherCalendar = Calendar.getInstance();
        anotherCalendar.add(Calendar.DATE, 1);
        System.out.println(calendar.compareTo(anotherCalendar));

    }
}

Output:

-1


Approach 2: NullPointerException

Java

import java.util.Calendar;

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

        // create a calendar
        Calendar calendar = Calendar.getInstance();
        Calendar anotherCalendar = null;
        System.out.println(calendar.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