In this tutorial, we'll learn how to check if a year is a leap year in Java using both loop and conditional statements. Leap year checks are often asked in coding interviews and programming challenges.
What is a Leap Year?
A leap year is a year that is evenly divisible by 4, except for years that are evenly divisible by 100, unless they are also divisible by 400. This means:
- 2020 is a leap year (divisible by 4).
- 1900 is not a leap year (divisible by 100, but not by 400).
- 2000 is a leap year (divisible by 400).
1️⃣ Leap Year Using Conditional Statements
public class LeapYear {
public static void main(String[] args) {
int year = 2020;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
}
2️⃣ Leap Year Using Loop
public class LeapYearLoop {
public static void main(String[] args) {
int startYear = 2000;
int endYear = 2020;
for (int year = startYear; year <= endYear; year++) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
}
}
🧠Interview Tip
In interviews, understanding leap year calculations is essential. Be sure to mention how leap years are calculated with the exception for centuries that aren't divisible by 400. Also, practice with both a single year check and checking multiple years, as shown in the second example.
✅ Output
2020 is a leap year.
📌 Conclusion
We have explored how to check for leap years using both conditional statements and a loop in Java. Understanding leap years is a great way to improve your coding skills and prepare for coding interviews.
For more such simple yet useful programs, check the Palindrome Number Program.