DEV Community

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

Posted on • Edited on

3 1

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)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.