Saturday, September 6, 2025
HomeLanguagesJavaYearMonth compareTo() method in Java

YearMonth compareTo() method in Java

The compareTo() method of YearMonth class in Java is used to compare two YearMonth objects. It compares this YearMonth object to the YearMonth object passed to it as parameter. The comparison between the two YearMonth instances is first done on the value of Year and then on the Month.

Syntax:  

public int compareTo(YearMonth otherYearMonth)

Parameter: This method accepts a single parameter otherYearMonth which is the other YearMonth instance with which this YearMonth is to be compared. 

Return Value: It returns an integral comparator value based on the comparison:  

  • It returns 1 is this YearMonth is greater than otherYearMonth.
  • It returns -1 is this YearMonth is less than otherYearMonth.
  • It returns 0 is this YearMonth is equals to otherYearMonth.

Below programs illustrate the compareTo() method of YearMonth in Java: 

Program 1:  

Java




// Program to illustrate the compareTo() method
 
import java.util.*;
import java.time.*;
 
public class GfG {
    public static void main(String[] args)
    {
 
        // Creates first YearMonth object
        YearMonth firstYearMonth = YearMonth.of(2017, 8);
 
        // Creates second YearMonth object
        YearMonth secondYearMonth = YearMonth.of(2016, 11);
 
        // compare the two YearMonth instances
        System.out.println(firstYearMonth.compareTo(secondYearMonth));
    }
}


Output: 

1

 

Program 2

Java




// Program to illustrate the compareTo() method
 
import java.util.*;
import java.time.*;
 
public class GfG {
    public static void main(String[] args)
    {
 
        // Creates first YearMonth object
        YearMonth firstYearMonth = YearMonth.of(2016, 11);
 
        // Creates second YearMonth object
        YearMonth secondYearMonth = YearMonth.of(2016, 11);
 
        // compare the two YearMonth instances
        System.out.println(firstYearMonth.compareTo(secondYearMonth));
    }
}


Output: 

0

 

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

RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS