Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other words, A year that is completely divisible by 4 is called leap year. In each leap year, the month of February has 29 days instead of 28. For example, 1998, 1992, 1996, 2020. In this section, we will create a Java program to check the given year is leap year or not.

Algorithm to Check Leap Year

  1. Assign a year to a variable which you want to check.
  2. Now, check the year is completely divisible by 400 or not. If the year is divisible by 400, the given year is a leap year.
  3. If the year is not divisible by 400, then check whether the year is divisible by 4 or not.
  4. If the given year is divisible by 4, then we need to check the year is divisible by 100 or not. If 100 perfectly divides the year then the year is not a leap year otherwise it is a leap year.
  5. If 4 does not divide the year perfectly, then the year is not a leap year.

Let’s implement the above algorithm in a Java program.

Filename: LeapYearExample.java

Output:

In the above program, we can also implement the logic in a single statement like the following:

Explanation: While writing the code, the concept of short-circuiting is used. That is why we have three return statements in the code. Short-circuiting means if, at any point, we can make a decision, we should not be moving further to check other expressions. In our case, if any year is divisible by 400, we can say the year is a leap year. Hence, no need to check its divisibility with 4 or 100, and we can stop right here. If 400 does not divide the year perfectly, we move further and check its divisibility with 4 and 100. If the year is divisible by 4 and not by 100, we have got the leap year; otherwise, the year is not a leap year.

Pin It on Pinterest

Share This