Is it a Leap Year?

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.

Use the 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. That means that 4 is divisible by 2.

Here is a code snippet that uses the modulo operator to check 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");
}

Here is the output:

2016 is a leap year

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

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