Java ProgramsControl FlowCheck Leap Year

Check Leap Year in Java

intermediate·  Control Flow  ·  Conditional Statements

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.

Input
2024
Output
2024 is a leap year: true

Java Program

Java
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

2024 is a leap year: true

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.

How It Works
  1. 1year % 4 == 0 checks the basic every-fourth-year rule.
  2. 2year % 100 != 0 excludes century years, which don't automatically qualify.
  3. 3year % 400 == 0 lets century years back in if they're also divisible by 400.
  4. 4The full condition is (divisible by 4 AND not divisible by 100) OR divisible by 400.
For 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

modulo operatorlogical AND/ORnested condition

Approach 2: Using Year.isLeap()

Java
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

2024 is a leap year: true

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.

How It Works
  1. 1Year.isLeap(year) is a static method on java.time.Year that applies the same divisible-by-4/100/400 rule internally.
  2. 2It takes a long year and returns a boolean directly.
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.

Key Concepts

java.time.YearisLeap()

Related Programs