Thursday, December 11, 2025
HomeLanguagesJavaMonthDay compareTo() method in Java with Examples

MonthDay compareTo() method in Java with Examples

The compareTo() method of MonthDay class in Java compares this month-day to another month-day.

Syntax:

public int compareTo(MonthDay other)

Parameter: This method accepts a parameter other which specifies the other month-day to compare to and not null.

Returns: The function returns the comparator value. It can be negative if it is less or positive if it is greater.

Exceptions: The function throws an NullPointerException if the other is null.

Below programs illustrate the MonthDay.compareTo() method:

Program 1:




// Program to illustrate the compareTo() method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
        // Parses the date
        MonthDay tm1 = MonthDay.parse("--12-06");
  
        // Uses the function
        LocalDate dt1 = tm1.atYear(2018);
  
        // Parses the date
        MonthDay tm2 = MonthDay.parse("--12-06");
  
        // Uses the function
        LocalDate dt2 = tm2.atYear(2018);
  
        // Prints the date
        System.out.println(dt1.compareTo(dt2));
    }
}


Output:

0

Program 2:




// Program to illustrate the compareTo() method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
        // Parses the date
        MonthDay tm1 = MonthDay.parse("--10-06");
  
        // Uses the function
        LocalDate dt1 = tm1.atYear(2018);
  
        // Parses the date
        MonthDay tm2 = MonthDay.parse("--12-06");
  
        // Uses the function
        LocalDate dt2 = tm2.atYear(2018);
  
        // Prints the date
        System.out.println(dt1.compareTo(dt2));
    }
}


Output:

-2

Program 3:




// Program to illustrate the compareTo() method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
        // Parses the date
        MonthDay tm1 = MonthDay.parse("--10-06");
  
        // Uses the function
        LocalDate dt1 = tm1.atYear(2018);
  
        // Parses the date
        MonthDay tm2 = MonthDay.parse("--09-06");
  
        // Uses the function
        LocalDate dt2 = tm2.atYear(2018);
  
        // Prints the date
        System.out.println(dt1.compareTo(dt2));
    }
}


Output:

1

Reference: https://docs.oracle.com/javase/8/docs/api/java/time/MonthDay.html#compareTo-java.time.MonthDay-

RELATED ARTICLES

Most Popular

Dominic
32440 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6811 POSTS0 COMMENTS
Nicole Veronica
11950 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12023 POSTS0 COMMENTS
Shaida Kate Naidoo
6942 POSTS0 COMMENTS
Ted Musemwa
7193 POSTS0 COMMENTS
Thapelo Manthata
6889 POSTS0 COMMENTS
Umr Jansen
6880 POSTS0 COMMENTS