Check For Leap Year in Java

Exercise:

Write a Java Program to check if the year is leap year or not.

Click Here to View the Solution!
public class LeapYearChecker {
    public static void main(String[] args) {
         int year = 2000;
         boolean leapYear = false;
  
         if(year % 4 == 0)
         {
             if( year % 100 == 0)
             {
// checks if the 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.");
     }
 } 
Click Here to View the Output!
2000 is a leap year.
Click Here to View the Explanation!
  • This program is used for checking that whether a year is a leap year or not and display the result.
  • The year 2000 is stored in an integer variable year. To find that whether 2000 is a leap year, it is divided by 4. Since, 2000 is a century year, that is a year ending at 00, it must be divisible by 400. 2000 is divisible by 4 and 400 both so it’s a leap year.
  • Considering the mathematical conditions for identifying a leap year, if the year is changed to another century year 1900, it must be divisible by 4 but not by 400. So the year 1900 is not a leap year.
  • Similarly, if the year 2016 is placed in the variable year, it is checked whether it is divisible by 4. There is no need to check if 2016 is divisible by 400 since it is not a century year. 2016 is divisible by 4 hence it is a leap year.
%d bloggers like this: