Leap Year Checker in Java
This program checks if a given year is a leap year. A year is a leap year if:
- It is divisible by 4
- Except for end-of-century years, which must be divisible by 400
- This means that the year 2000 was a leap year, although 1900 was not
Program Structure and Explanation
The Java program follows these steps:
- Define the
isLeapYear
method which takes an integer year as an argument. - Check if the year is divisible by 4.
- If true, check if the year is also divisible by 100.
- If true, check if the year is divisible by 400.
- If any condition fails, return false; otherwise, return true if all conditions pass.
- Test the method with a sample year.
Java Program
/**
* This class provides a method to check if a given year is a leap year.
*/
public class LeapYearChecker {
/**
* Checks if a given year is a leap year.
*
* @param year the year to check
* @return true if the year is a leap year, false otherwise
*/
public static boolean isLeapYear(int year) {
// A leap year is divisible by 4
if (year % 4 == 0) {
// If the year is also divisible by 100, it must be divisible by 400 to be a leap year
if (year % 100 == 0) {
return year % 400 == 0;
} else {
return true; // If not divisible by 100, it is a leap year
}
} else {
return false; // Not divisible by 4, not a leap year
}
}
/**
* Main method to test the isLeapYear method.
*
* @param args command-line arguments
*/
public static void main(String[] args) {
int year = 2024; // Example year to test
if (isLeapYear(year)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
}
Explanation of the Code
The isLeapYear
method first checks if the year is divisible by 4. If it is, the method then checks if the year is also divisible by 100. If both conditions are true, the method checks if the year is divisible by 400. If the year passes all these checks, it is a leap year; otherwise, it is not. The main
method demonstrates how to use the isLeapYear
method with an example year.