Check if a year is a leap year
Description: Write a method isLeap(int year). A year is a leap year if it is divisible by 4, but not by 100, unless it is divisible by 400. Test 1900, 2000, 2024 and 2026.
Hint:
- Use the remainder operator
%.
Solution
public class Main {
static boolean isLeap(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
public static void main(String[] args) {
for (int y : new int[]{1900, 2000, 2024, 2026}) {
System.out.println(y + " -> " + isLeap(y));
}
System.out.println(java.time.Year.isLeap(2024)); // the library method
}
}
Output
1900 -> false
2000 -> true
2024 -> true
2026 -> false
true
How it works
- 1900 is divisible by 100 but not by 400, so it is not a leap year. 2000 is divisible by 400, so it is.
- Java has this check ready:
Year.isLeap().
Read Java Operators.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |