Java Program to Check Leap Year

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.

Example: Java Program to Check a Leap Year

  1. public class LeapYear {
  2. public static void main(String[] args) {
  3. int year = 1900;
  4. boolean leap = false;
  5. if(year % 4 == 0)
  6. {
  7. if( year % 100 == 0)
  8. {
  9. // year is divisible by 400, hence the year is a leap year
  10. if ( year % 400 == 0)
  11. leap = true;
  12. else
  13. leap = false;
  14. }
  15. else
  16. leap = true;
  17. }
  18. else
  19. leap = false;
  20. if(leap)
  21. System.out.println(year + " is a leap year.");
  22. else
  23. System.out.println(year + " is not a leap year.");
  24. }
  25. }

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.