Java Program to Check Leap Year with Output and Explanation
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) to print that the year is leap; otherwise, it is not leap.Examples
How to Think About It
Algorithm
Code
import java.util.Scanner; public class LeapYearCheck { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a year: "); int year = scanner.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"); } scanner.close(); } }
Dry Run
Let's trace the year 1900 through the code
Input year
year = 1900
Check divisibility by 400
1900 % 400 = 300 (not zero), so false
Check divisibility by 4 and not by 100
1900 % 4 = 0 (true), 1900 % 100 = 0 (true), so condition false because divisible by 100
Result
Year is not a leap year
| Condition | Result |
|---|---|
| year % 400 == 0 | false |
| year % 4 == 0 && year % 100 != 0 | false |
| Leap year? | No |
Why This Works
Step 1: Divisible by 400 means leap year
If year % 400 == 0 is true, the year is a leap year because every 400 years the calendar corrects itself.
Step 2: Divisible by 4 but not by 100 means leap year
If the year is divisible by 4 but not by 100, it is a leap year because most leap years follow this rule.
Step 3: Other years are not leap years
If neither condition is true, the year is not a leap year.
Alternative Approaches
import java.time.Year; public class LeapYearCheck { public static void main(String[] args) { int year = 2020; if (Year.isLeap(year)) { System.out.println(year + " is a leap year"); } else { System.out.println(year + " is not a leap year"); } } }
import java.util.Scanner; public class LeapYearCheck { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a year: "); int year = scanner.nextInt(); if (year % 400 == 0) { System.out.println(year + " is a leap year"); } else if (year % 100 == 0) { System.out.println(year + " is not a leap year"); } else if (year % 4 == 0) { System.out.println(year + " is a leap year"); } else { System.out.println(year + " is not a leap year"); } scanner.close(); } }
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of arithmetic and logical operations regardless of input size, so it runs in constant time O(1).
Space Complexity
The program uses a fixed amount of memory for variables and does not allocate extra space based on input, so space complexity is O(1).
Which Approach is Fastest?
All approaches run in constant time, but using Java's built-in Year.isLeap() method is more readable and less error-prone.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual condition check | O(1) | O(1) | Simple and clear logic |
| Java Year.isLeap() method | O(1) | O(1) | Readability and built-in reliability |
| Nested if-else | O(1) | O(1) | Explicit condition handling |