Friday, October 17, 2025
HomeLanguagesJavaYear compareTo() method in Java with Examples

Year compareTo() method in Java with Examples

The compareTo() method of Year class in Java is used to compare this Year object with another Year object. The comparison of Year object is based on the values of Year.
Syntax
 

public int compareTo(Year otherYear)

Parameter: This method accepts a single parameter otherYear. It is the Year object which specifies a year with which we want to compare the current year object.
Return Value: It returns an integral comparator value based on the comparison of the two Year objects.
Below programs illustrate the compareTo() method of Year in Java: 
Program 1: In this program the value of current Year object is less than the second year object. So, the value returned is -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 Year object
        Year firstYear = Year.of(2017);
 
        // Creates second year object
        Year secondYear = Year.of(2018);
 
        // Compare the two years and print the
        // comparator value
        System.out.println(firstYear.compareTo(secondYear));
    }
}


Output: 

-1

 

Program 2: In this program the value of current Year object is equals to the second year object. So, the value returned is 0. 
 

Java




// Program to illustrate the compareTo() method
 
import java.util.*;
import java.time.*;
 
public class GfG {
    public static void main(String[] args)
    {
        // Creates first Year object
        Year firstYear = Year.of(2018);
 
        // Creates second year object
        Year secondYear = Year.of(2018);
 
        // Compare the two years and print the
        // comparator value
        System.out.println(firstYear.compareTo(secondYear));
    }
}


Output: 

0

 

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

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS