Check Leap Year in Java
Problem
A year is a leap year when it's divisible by 4, except century years, which must also be divisible by 400 to qualify.
Given a year, determine whether it is a leap year.
Java Program
public class LeapYearCheck {
public static void main(String[] args) {
int year = 2024;
boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); // century years need the /400 exception
System.out.println(year + " is a leap year: " + isLeap);
}
}Output
Core Logic
The leap-year rule has an exception built into an exception — divisibility by 4 qualifies a year, unless it's also a century year that fails the stricter divisible-by-400 test.
- 1
year % 4 == 0checks the basic every-fourth-year rule. - 2
year % 100 != 0excludes century years, which don't automatically qualify. - 3
year % 400 == 0lets century years back in if they're also divisible by 400. - 4The full condition is
(divisible by 4 AND not divisible by 100) OR divisible by 400.
year = 2024, it's divisible by 4 and not divisible by 100, so the first half of the condition is true and 2024 is a leap year.Key Point: Century years are the whole reason this rule needs three checks instead of one — 1900 is divisible by 4 but isn't a leap year, while 2000 is divisible by 4 and by 400, so it is.
Key Concepts
Approach 2: Using Year.isLeap()
import java.time.Year;
public class LeapYearCheckBuiltIn {
public static void main(String[] args) {
int year = 2024;
boolean isLeap = Year.isLeap(year);
System.out.println(year + " is a leap year: " + isLeap);
}
}
Output
Core Logic
Java's date-and-time API already encodes the leap-year rule, so the three-part condition never has to be written out by hand.
- 1
Year.isLeap(year)is a static method onjava.time.Yearthat applies the same divisible-by-4/100/400 rule internally. - 2It takes a
longyear and returns abooleandirectly.
Year.isLeap(2024) returns true.Key Point: Reaching for the standard library here avoids re-deriving a rule that's easy to get subtly wrong, like forgetting the century-year exception, when written from scratch.