Java Program to Check Leap Year

Learn to check if the given year is a leap year or not, using different Java date-time classes.

A leap year is :

  • exactly divisible by 4 except for century years (years ending with 00).
  • a century year only if it is divisible by 400. For example, 2000 was a leap year. The next century leap year will be 2400.

1. Checking Leap Year with LocalDate

Given examples use the LocalDate.isLeapYear() and Year.isLeap() methods to determine if the year associated with a given instance is a leap year or not. We can invoke similar methods with ZonedDateTime, LocalDateTime classes.

We can use now() method to get the current date instance that will help in checking if the current year is a leap year or not.

LocalDate localDate = LocalDate.now();

boolean isLeapYear = localDate.isLeapYear();  //true or false

//or

boolean isLeapYear = Year.now().isLeap();

2. Checking Leap Year till Java 7

In legacy Java APIs, primary classes to handle date and time were Date, Calendar and GregorianCalendar. To determine the leap year, we have two approaches:

  1. GregorianCalendar.isLeapYear(int year)
  2. Custom method to determine leap year

No matter what approach we use, we must extract the year value from any given date or calendar instance and then use any of the above methods.

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Main
{
    public static void main(String[] args)
    {
        // 1. Calendar
        Calendar cal = Calendar.getInstance();
        System.out.println( isLeapYear(cal.get(Calendar.YEAR)) );

        //2. Date
        Date date = new Date();
        System.out.println( isLeapYear(date.getYear()) );

        //3. GregorianCalendar
        GregorianCalendar gc = new GregorianCalendar();
        System.out.println( gc.isLeapYear(gc.get(GregorianCalendar.YEAR)) );
    }

    private static boolean isLeapYear(int year)
    {
        //1583 was the first year of the Gregorian Calendar
        assert year >= 1583; 

        return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
    }
}

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial