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:
- The year is divisible by 400.
- 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");
}
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.
Top comments (0)