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 comaprison:
- 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:
// 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)); } } |
1
Program 2:
// Programt 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)); } } |
0
Reference: https://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html#compareTo-java.time.YearMonth-
Recommended Posts:
- YearMonth atEndOfMonth() method in Java
- YearMonth until() Method in Java with Examples
- YearMonth equals() method in Java
- YearMonth format() method in Java
- YearMonth getMonth() method in Java
- YearMonth lengthOfMonth method() in Java
- YearMonth getMonthValue() method in Java
- YearMonth hashCode() method in Java
- YearMonth getYear() method in Java
- YearMonth with() Method in Java with Examples
- YearMonth atDay() method in Java
- YearMonth plus(TemporalAmount) method in Java with Examples
- YearMonth withYear() method in Java with Examples
- YearMonth range() method in Java with Examples
- YearMonth lengthOfYear() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



