How to Find Leap Year in Java

Learn to check if the given year is a leap year or not, using different Java date-time classes. In Java, finding leap years involves a logical approach, and developers can leverage built-in classes for efficient solutions.

A leap year occurs every four years, with a slight twist. Years divisible by 100 are not leap years unless they are divisible by 400. This rule fine-tunes the alignment of the calendar to account for the extra 0.2422 days in Earth’s orbit.

1. Finding Leap Year in Java 8

Java 8 introduced the java.time package and the following classes (and methods) that can help determine if a given year is a leap year or not.

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

LocalDate ldt = LocalDate.now();
boolean isLeapYear = ldt.isLeapYear();

//or

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

2. Finding 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:

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

The second method uses the leap year definition directly, checking for divisibility by 4, and non-divisibility by 100 (unless divisible by 400) to determine leap years.

// 1
public static boolean isLeapYearUsingGregorianCalendar(int year) {
  GregorianCalendar calendar = new GregorianCalendar();
  return calendar.isLeapYear(year);
}

// 2
public static boolean isLeapYear(int year) {
  if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
    return true;
  } else {
    return false;
  }
}

3. Conclusion

In Java, finding leap years is essential in several usecases such as date validation to ensure accurate and reliable date inputs or interest calculations, loan repayments, and other financial activities that involve the accurate measurement of time.

Whether using the GregorianCalendar class, the modern java.time.Year class, or a straightforward algorithmic approach, developers have various options for finding a given year is a leap year or not.

Happy Learning !!

Comments

Subscribe
Notify of
guest
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

Dark Mode

Dark Mode