Leap Year Program in Java
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
- Assign a year to a variable which you want to check.
- 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.
- If the year is not divisible by 400, then check whether the year is divisible by 4 or not.
- 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.
- 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
public class LeapYearExample { private static boolean isLeapYear(int n) { if(n % 400 == 0) // Checking divisibility by 400. 1st step of the algorithm return true; //Implementing 3rd and the 4th step of the algorithm if((n % 4 == 0) && (n % 100 != 0)) return true; return false; } public static void main(String[] args) { int arr[] = {1998, 1999, 1990, 2000, 2010, 2016, 2020, 2040, 2100}; for(int i = 0; i < arr.length; i++) //Iterating over each element { if(isLeapYear(arr[i])) // Checking leap year for each element System.out.println(arr[i] + " is a leap year"); else System.out.println(arr[i] + " is not a leap year"); } } }
Output:
1998 is not a leap year 1999 is not a leap year 1990 is not a leap year 2000 is a leap year 2010 is not a leap year 2016 is a leap year 2020 is a leap year 2040 is a leap year 2100 is not a leap year
In the above program, we can also implement the logic in a single statement like the following:
if(((year%4==0) && ((year%400==0) || (year%100!==0))
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.