How do I check if a year is a leap year?

The following example using the GregorianCalendar.isLeapYear() method to check if the specified year is a leap year.

package org.kodejava.util;

import java.util.GregorianCalendar;

public class LeapYearExample {
    public static void main(String[] args) {
        // Here we show how to know if a specified year is a leap year or 
        // not. The GregorianCalendar object provide a convenient method 
        // to do this. The method is GregorianCalendar.isLeapYear().

        // First, let's obtain an instance of GregorianCalendar.
        GregorianCalendar cal = new GregorianCalendar();

        // The isLeapYear(int year) method will return true for leap 
        // year and otherwise return false. In this example the message 
        // will be printed as 2020 is a leap year.
        if (cal.isLeapYear(2020)) {
            System.out.println("The year 2020 is a leap year!");
        }
    }
}

The result of our code is:

The year 2020 is a leap year!

Another code for checking leap year can be seen in the following example How do I know if a given year is a leap year?.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.