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.example.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 2016 is a leap year.
        if (cal.isLeapYear(2016)) {
            System.out.println("The year 2016 is a leap year!");
        }
    }
}

The result of our code is:

The year 2016 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

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.

Leave a Reply