Java Program to Check Leap Year
A leap year is a year that has 366 days instead of 365 days, with February having 29 days. Leap year logic is a common beginner programming problem in Java.
In this tutorial, we will create a Java program to check whether a given year is a leap year or not.
By the end of this guide, you will understand how to use conditional logic to solve real-world problems in Java.
Concept Overview
A year is a leap year if it follows these rules:
1. It is divisible by 4. 2. If it is divisible by 100, it must also be divisible by 400.
Program
import java.util.Scanner;
public class LeapYearCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = sc.nextInt();
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");
}
}
}
Output
Enter a year: 2024
2024 is a Leap Year
Detailed Explanation
The program starts by taking input from the user using the Scanner class.
The year is checked using a combination of logical operators.
If the year is divisible by 4 and not divisible by 100, or divisible by 400, it is a leap year.
Otherwise, it is not a leap year.
Example Walkthrough
Let us consider the year 2024.
2024 % 4 = 0 and 2024 % 100 ≠ 0, so it is a leap year.
Applications
Leap year logic is used in calendars, scheduling systems, and date calculations.
Advantages of This Approach
This program helps beginners understand complex conditional logic.
It demonstrates the use of multiple logical operators together.
Limitations
The program only checks valid integer input and does not validate incorrect formats.
Improvements You Can Make
You can extend this program to process a range of years.
You can also integrate it into a calendar application.
This Java program strengthens understanding of conditional logic and real-world decision making.
Codecrown