1. Overview
In this tutorial, you'll learn how to check the given year is a leap year or not.
Everyone knows that leap year comes for every 4 years and February month with 29 days.
But, when we do the logic in java it is bit different and should know the complete formula to evaluate leap year.
For example, year 2012 is a leap year which is divided by 4 and February month has 29 days.
Su Mo Tu We Th Fr Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29
Take another year 1900 which is perfectly divided by 4 but February month has only 28 days rather than 29.
1900
February
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28
So, year 1900 is not a leap year.
Core rule for leap year is if and only if a year is divided by 4 except years ending with 00. If the year is ending with 00 and if it is divided by 100 then it must be divided by 400 also then only it is a leap year, otherwise not.
2. Example Program To Check Leap Year or Not
In the below example, we will check all the following checks.
Step 1: year is divided by 4 if yes go to step 2. Otherwise not leap year.
Step 2: next, check year is divided by 100 (ending with 00). If yes go to step 3, else it is leap year.
Step 3: Next check year is divided by 400 then it is is leap year other wise it is not a leap year.
package com.javaprogramto.programs; public class LeapYearExample { public static void main(String[] args) { int year = 1700; boolean leapyear = false; // step 1: year is divisible by 4 if (year % 4 == 0) { // step 2: if year is divisible by 100 if (year % 100 == 0) { // step 3 year is divisible by 400, hence the year is a leap year if (year % 400 == 0) leapyear = true; else leapyear = false; } else leapyear = true; } else leapyear = false; if (leapyear) System.out.println(year + " is a leap year"); else System.out.println(year + " is not a leap year"); } }
Output:
1700 is not a leap year
3. Conclusion
In this article, you have seen how to check the year is leap or not.
Example program shown is over GitHub.
No comments:
Post a Comment
Please do not add any spam links in the comments section.