Pages

Wednesday, October 23, 2019

Java Program to Check Leap Year

1. Introduction:


In this program, you'll learn to check if the given year is a leap year or not. This is checked using a if else statement.

A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400.

Java Program to Check Leap Year




2. Example Program: Java Program to Check a Leap Year


public class LeapYear {
    public static void main(String[] args) {
        int year = 1900;
        boolean leap = false;
        if(year % 4 == 0)
        {
            if( year % 100 == 0)
            {
                // year is divisible by 400, hence the year is a leap year
                if ( year % 400 == 0)
                    leap = true;
                else
                    leap = false;
            }
            else
                leap = true;
        }
        else
            leap = false;
        if(leap)
            System.out.println(year + " is a leap year.");
        else
            System.out.println(year + " is not a leap year.");
    }
}


Output:

When you run the program, the output will be:

1900 is not a leap year.

When you change the value of year to 2012, the output will be:

2012 is a leap year.

In the above program, given year 1900 is stored in the variable year.

Since 1900 is divisble by 4 and is also a century year (ending with 00), it has be divisble by 400 for a leap year. Since it's not divisible by 400, 1900 is not a leap year.

But, if we change year to 2000, it is divisible by 4, is a century year and is also divisible by 400. So, 2000 is a leap year.

Likewise, If we change year to 2012, it is divisible by 4 and is not a century year, so 2012 a leap year. We don't need to check if 2012 is divisible by 400 or not.

3. Conclusion


The year is a leap year if it has 366 days and year is not a leap year if it has 365 days.

We've seen the example program to find the given year is leap or not.


No comments:

Post a Comment

Please do not add any spam links in the comments section.