DEV Community

Cover image for Is it a Leap Year?
Edwin Torres
Edwin Torres

Posted on • Updated on

Is it a Leap Year?

There is a simple, mathematical way to determine if a year is a leap year.

A year is a leap year if it satisfies either of these conditions:

  1. The year is divisible by 400.
  2. The year is divisible by 4 and not divisible by 100.

It is easy to check for a leap year in a Java program. Use the Java modulo operator (%) to determine if a number is divisible by another number. The modulo operator returns the remainder when dividing a number by another number. For example, 4 % 2 is 0. Since the remainder is 0, it means that 4 is divisible by 2.

A simple Java program can use an if statement, the modulo operator, and some conditions to determine if a year is a leap year.

Here is a Java code snippet that checks if 2016 is a leap year:

int year1 = 2016;
if ((year1 % 400 == 0) || (year1 % 4 == 0 && year1 % 100 != 0)) {
  System.out.println(year1 + " is a leap year");
} else {
  System.out.println(year1 + " is NOT a leap year");
}
Enter fullscreen mode Exit fullscreen mode

Here is the output:

2016 is a leap year
Enter fullscreen mode Exit fullscreen mode

2016 is a leap year. The code snippet above determines that correctly.

Follow me on Twitter @realEdwinTorres for more programming tips and help.

Top comments (0)