72. Checking for a leap year
This problem becomes easy as long as we know what a leap year is. In a nutshell, a leap year is any year divisible by 4 (so, year % 4 == 0
) that it is not a century (for instance, 100, 200, …, n00). However, if the year represents a century that is divisible by 400 (so, year % 400 == 0
), then it is a leap year. In this context, our code is just a simple chain of if
statements as follows:
public static boolean isLeapYear(int year) {
if (year % 4 != 0) {
return false;
} else if (year % 400 == 0) {
return true;
} else if (year % 100 == 0) {
return false;
}
return true;
}
But, this code can be condensed using the GregorianCalendar
as well:
public static boolean isLeapYear(int year) {
return new GregorianCalendar(year, 1, 1).isLeapYear(year);
}
Or, starting with JDK 8, we can rely on the java.time.Year
API as follows:
public static boolean isLeapYear(int year) {
return Year.of(year).isLeap();
}
In...