compareTo(Date): This method is available in java.util.Date class of Java.
Syntax:
int java.util.Date.compareTo(Date anotherDate)
This method takes one argument of type Date as its parameter. This method compares two Dates for ordering.
Parameters: One parameter is required for this method.
anotherDate: the Date to be compared.
Returns:
1. The value 0 if the argument Date is equal to this Date.
2. A value less than 0 if this Date is before the Date argument.
3. A value greater than 0 if this Date is after the Date argument.
Throws:
NullPointerException - if anotherDate is null.
Approach 1: When no exception
Java
import java.util.Date;public class DatecompareTo {public static void main(String[] args) {Date date = new Date();Date anotherDate = new Date();System.out.println(date.compareTo(anotherDate));}}
Output:
0
Approach 2: NullPointerException
Java
import java.util.Date;public class DatecompareTo {public static void main(String[] args) {Date date = new Date();Date anotherDate = null;System.out.println(date.compareTo(anotherDate));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "date" is null at java.base/java.util.Date.getMillisOf(Date.java:957) at java.base/java.util.Date.compareTo(Date.java:980)
No comments:
Post a Comment