This program is checking if a given year is a leap year or not.
A normal year has 365 days. Every four years, however, there is a leap year with 366 days. This is because the earth does not need exactly 365 days to travel once around the sun, but about a quarter day more. So a year has one day more every 4 years.
So that the calculation is correct, there is no leap year every 100 years. Nevertheless, every four hundred years a leap year takes place. This concerns the years 2000, 2400 etc.
class CheckLeapYearExample {
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;
} else {
return true;
}
}
public static void main(String[] args) {
int year = 2020;
if (isLeapYear(year)) {
System.out.println(year + " is a leap year");
} else {
System.out.println(year + " is not a leap year");
}
}
}
2020 is a leap year
The program has a static method isLeapYear
which takes an integer argument year
and returns a boolean value. The method first checks if the year is not divisible by 4, it returns false, because a leap year must be divisible by 4. If it is divisible by 4, it checks if it is divisible by 400, if it is, it returns true, because a year that is divisible by 400 is always a leap year. If it’s not divisible by 400, it checks if it’s divisible by 100, if it is, it returns false, because a year that is divisible by 100 but not divisible by 400 is not a leap year. If it’s not divisible by 100, it returns true because it is a leap year.
In the main method, an integer variable year
is declared and assigned a value of 2020. The program then calls the isLeapYear
method and passes the value of year
as an argument. The returned value of isLeapYear
is then used in an if-else statement to determine if the year is a leap year or not. If it is a leap year, a message is printed saying the year is a leap year, and if it’s not, a message is printed saying the year is not a leap year.