Leap Year Program in Java: Simple Code Examples

Published: 20 Nov 2025 | Reading Time: 5 min read

Table of Contents

What This Blog Delivers

This comprehensive guide provides complete coverage of leap year programming in Java:

Introduction

"Programs that handle dates may look simple, but one wrong condition can break an entire system."

Every Java student writes a "Leap Year Program" at least once, yet few truly understand why leap years exist or how they impact real-world applications like:

If you've wondered why February suddenly has 29 days, or why 2000 is a leap year but 1900 is not, this guide explains the exact logic companies expect you to write correctly in coding interviews and assessments.

This blog provides simple, clear, and complete implementations of leap year checking in Java, from beginner-friendly If-Else logic to professional methods using Year.of(year).isLeap().

What is a Leap Year?

A leap year is a year that has an extra day added to February, making the month 29 days instead of the usual 28 days. This adjustment happens every 4 years to align the calendar with Earth's orbit, which takes 365.25 days.

Important Exception: Not every year divisible by 4 is a leap year. Century years (years ending in 00) are a special case. A century year is only considered a leap year if it is divisible by 400.

Examples:

Rules to Verify a Leap Year Program in Java

A Java program for leap year must follow these rules:

  1. Rule 1: If the year is divisible by 4, it can be a leap year → Move to next check
  2. Rule 2: If the year is divisible by 100, we need one more condition to confirm
  3. Rule 3: If the year is also divisible by 400, then it is a leap year
  4. Rule 4: If the year is not divisible by 100 but is divisible by 4, it is still a leap year
  5. Rule 5: If none of the above conditions are met, then the year is not a leap year

A leap year code in Java automates this logic and helps you understand how to solve similar problems in programming.

Steps to Find If Given Year Is Leap Year

The leap year program in Java follows these steps:

Step 1: Determine whether the year is divisible by four. It's not a leap year if not.

Step 2: Determine whether the year is a century year (ending in 00) if it is divisible by 4. It's a leap year if it's not a century year.

Step 3: If the year is a century year, check if it is divisible by 400. If yes, it's a leap year; if no, it's not a leap year.

Algorithm

  1. Start
  2. Enter the user's year
  3. Check if the year is divisible by 4:
    • If yes, go to step 4
    • If no, print "Not a leap year" and go to step 7
  4. Check if the year is divisible by 100:
    • If yes, go to step 5
    • If no, print "Leap year" and go to step 7
  5. Verify whether the year can be divided by 400:
    • Print "Leap year" if that's the case
    • If not, print "Not a leap year"
  6. End

Pseudocode For Leap Year Program in Java

Start
    Input year
    If year is divisible by 4
        If year is divisible by 100
            If year is divisible by 400
                Print "Leap year"
            Else
                Print "Not a leap year"
        Else
            Print "Leap year"
    Else
        Print "Not a leap year"
End

Output Example

Input Year: 2024
Output: 2024 is a leap year

This pseudocode for the leap year program in Java outlines the steps to check if a given year is a leap year. It checks the divisibility of the given year by 4, 100, and 400 to determine if the year meets the leap year conditions.

Java Program For Leap Year

This section demonstrates the basic implementation of a leap year program in Java using if-else statements.

1. Java Program For Leap Year Using if-else Statements

Pseudocode

Begin
Set a variable year to 2024
Test whether year can be evenly divided by 4
If it can, check whether it is also divisible by 100
If it is divisible by 100, verify whether it is divisible by 400
If so, it means this year is a leap year.
If no then display that the year is Not a Leap Year
If it is not divisible by 100 then display that the year is a Leap Year
If it is not divisible by 4 then display that the year is Not a Leap Year
End

Code

public class Main {
    public static void main(String[] args) {
        int year = 2024; // Year is hardcoded (no Scanner, no command line input)

        if (year % 4 == 0) {
            if (year % 100 == 0) {
                if (year % 400 == 0) {
                    System.out.println(year + " is a Leap Year");
                } else {
                    System.out.println(year + " is Not a Leap Year");
                }
            } else {
                System.out.println(year + " is a Leap Year");
            }
        } else {
            System.out.println(year + " is Not a Leap Year");
        }
    }
}

How The Code Works

Output

2024 is a Leap Year

=== Code Execution Successful ===

Complexity

Time Complexity: O(1)
Space Complexity: O(1)

Alternative Implementation Methods for Leap Year Program in Java

Checking whether a year is a leap year in Java can be done in several ways, depending on your use case: basic logic building, cleaner syntax, or using built-in date utilities. These approaches help you understand both leap year rules and how different Java features work in real programs.

1. Leap Year Program in Java Using If–Else Statements (Beginner-Friendly)

When you're just starting with Java, the simplest and most understandable approach is using if–else statements. This method clearly walks you through each rule of determining whether a year is a leap year or not. It teaches strong logic flow, helps you understand leap year rules, and prepares you for writing your first leapyearchecker class.

Pseudocode

Start
    Input year

    If year % 4 == 0
        If year % 100 == 0
            If year % 400 == 0
                Print "Leap Year"
            Else
                Print "Not a Leap Year"
            End If
        Else
            Print "Leap Year"
        End If
    Else
        Print "Not a Leap Year"
    End If
End

Java Code Using If–Else

public class LeapYearChecker {
    public static void main(String[] args) {
        int year = 2024; // Example year (can be changed)

        if (year % 4 == 0) {
            if (year % 100 == 0) {
                if (year % 400 == 0) {
                    System.out.println(year + " is a Leap Year");
                } else {
                    System.out.println(year + " is Not a Leap Year");
                }
            } else {
                System.out.println(year + " is a Leap Year");
            }
        } else {
            System.out.println(year + " is Not a Leap Year");
        }
    }
}

Output

2024 is a Leap Year

Complexity

Time Complexity: O(1)
Space Complexity: O(1)

Best for: Learning fundamental logic, understanding leap year rules step-by-step

2. Leap Year Program in Java Using Ternary Operator

A more concise method uses the ternary operator to compress all leap-year conditions into a single line. This helps create short, readable code, especially useful in competitive programming or quick checks.

Best for: Practicing expression-based logic, reducing nested conditions

Pseudocode

Start

Create a Scanner object to take user input.

Prompt the user to enter a year.

Read the entered value and store it in the variable 'year'.

Use the ternary operator to determine whether the year is a leap year:

   If (year % 4 == 0):
        If (year % 100 == 0):
             If (year % 400 == 0):
                 Set result = "Leap Year"
             Else:
                 Set result = "Not a Leap Year"
        Else:
             Set result = "Leap Year"
   Else:
        Set result = "Not a Leap Year"

Display the result along with the input year.

End

Code

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        // Input the year
        System.out.print("Enter a year: ");
        int year = scanner.nextInt();

        // Check if the year is a leap year using the ternary operator
        String result = (year % 4 == 0)
                ? ((year % 100 == 0)
                    ? ((year % 400 == 0) ? "Leap Year" : "Not a Leap Year")
                    : "Leap Year")
                : "Not a Leap Year";

        // Output the result
        System.out.println(year + " is " + result);

        scanner.close();
    }
}

How The Code Works

The ternary operator is used to replace the if-else statements:

Ternary operator logic:

Output

Enter a year: 2004
2004 is Leap Year

=== Code Execution Successful ===

Complexity

Time Complexity: O(1)
Space Complexity: O(1)

3. Java Program For Leap Year: Bonus Boolean Method

Here's the Java program for checking leap year in Java using a Boolean method:

Pseudocode

Start
Create a Scanner object for user input.
Prompt the user to enter a year.
Read the input and store it in the variable year.
Call the function isLeapYear(year) to check if the year is a leap year.
Inside the isLeapYear(year) function:
	If year is divisible by 4:
	Check if year is divisible by 100:
	If true, check if year is divisible by 400:
	If true, return true (Leap Year).
	Else, return false (Not a Leap Year).
	Else, return true (Leap Year).
	Else, return false (Not a Leap Year).
If isLeapYear(year) returns true, print "year is a Leap Year".
Else, print "year is Not a Leap Year".
End

Code

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the year
        System.out.print("Enter a year: ");
        int year = scanner.nextInt();

        // Call the isLeapYear method
        if (isLeapYear(year)) {
            System.out.println(year + " is a Leap Year");
        } else {
            System.out.println(year + " is Not a Leap Year");
        }
    }

    // Method to check if a year is a leap year
    public static boolean isLeapYear(int year) {
        if (year % 4 == 0) {
            if (year % 100 == 0) {
                return year % 400 == 0;
            }
            return true;
        }
        return false;
    }
}

How the Code Works

The program defines a separate Boolean method isLeapYear() to check if a year is a leap year.

Output

Enter a year: 2010
2010 is Not a Leap Year

=== Code Execution Successful ===

Complexity

Time Complexity: O(1)
Space Complexity: O(1)

4. Java Program For Leap Year Using Scanner Class

Any of the above methods can be paired with the Scanner class to allow users to enter a year dynamically. This creates a complete, interactive program.

Pseudocode

Begin
Create an input reader to accept a year from the user
Display a message asking the user to enter a year
Store the entered value in a variable named year
Check whether year is divisible by 4
	If it is, check whether it is divisible by 100
		If it is, check whether it is divisible by 400
			If yes → output that the year is a Leap Year
			Otherwise → output that the year is Not a Leap Year
		If it is not divisible by 100 → output that it is a Leap Year
	If it is not divisible by 4 → output that it is Not a Leap Year
Stop

Code

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a year: ");
        int year = input.nextInt();
        boolean isLeap;
        if (year % 4 == 0) {
            if (year % 100 == 0) {
                isLeap = (year % 400 == 0);
            } else {
                isLeap = true;
            }
        } else {
            isLeap = false;
        }
        if (isLeap) {
            System.out.println(year + " is a Leap Year");
        } else {
            System.out.println(year + " is Not a Leap Year");
        }
    }
}

How the Code Works

  1. First, we import the Scanner class from java.util package. The Scanner class is used to get input from the user.

    • Scanner scanner = new Scanner(System.in); initialises the scanner
    • scanner.nextInt(); reads an integer input (the year)
  2. The program evaluates the conditions to check if the year is a leap year:

    • Divisible by 4
    • If divisible by 100, also divisible by 400
  3. It prints whether the year is a leap year or not

Output

Enter a year: 2025
2025 is Not a Leap Year

=== Code Execution Successful ===

Complexity

Time Complexity: O(1)
Space Complexity: O(1)

5. Java Program For Leap Year Without Using Scanner Class

Here's the Java program to check leap year without using the Scanner class:

Pseudocode

Start
Initialize the variable year with the value 2024.
Check if year is divisible by 4:
	If true, check if year is divisible by 100:
	If true, check if year is divisible by 400:
	If true, print "year is a Leap Year".
	Else, print "year is Not a Leap Year".
	Else, print "year is a Leap Year".
	Else, print "year is Not a Leap Year".
End

Code

public class Main {
    public static void main(String[] args) {
        // Year is provided directly in the program
        int year = 2024;

        // Check if the year is a leap year
        if (year % 4 == 0) {
            if (year % 100 == 0) {
                if (year % 400 == 0) {
                    System.out.println(year + " is a Leap Year");
                } else {
                    System.out.println(year + " is Not a Leap Year");
                }
            } else {
                System.out.println(year + " is a Leap Year");
            }
        } else {
            System.out.println(year + " is Not a Leap Year");
        }
    }
}

How the Code Works

  1. The year is hardcoded into the program instead of being input dynamically

    • For example, in this program, year = 2024
  2. The program uses the same conditional checks as before:

    • Divisible by 4
    • If any number can be divided by 100, it must also be divided by 400
  3. Since it is divisible, it prints that 2024 is a leap year

Output

2024 is a Leap Year

=== Code Execution Successful ===

Complexity

Time Complexity: O(1)
Space Complexity: O(1)

6. Java Program For Leap Year Using In-built isLeap() Method

In this implementation, we'll look at the code for the Java program for leap year using the built-in isLeap() method:

Pseudocode

Start
Create a Scanner object to take user input.
Prompt the user to enter a year.
Read the input year and store it in the variable year.
Use the Year.of(year).isLeap() method to check if the year is a leap year:
	Print "year is a Leap Year" if this is the case.
	Print "year is Not a Leap Year" else.
End

Code

import java.time.Year;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Create a Scanner object for user input
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter a year
        System.out.print("Enter a year: ");
        int year = scanner.nextInt();

        // Check if the year is a leap year using isLeap() method
        if (Year.of(year).isLeap()) {
            System.out.println(year + " is a Leap Year");
        } else {
            System.out.println(year + " is Not a Leap Year");
        }
    }
}

How the Code Works

  1. The program uses the Scanner class to take user input for the year

  2. The Year.of(year).isLeap() method determines if the entered year is a leap year

  3. It prints the result based on the method's return value (true or false)

Output

Enter a year: 2028
2028 is a Leap Year

=== Code Execution Successful ===

Complexity

Time Complexity: O(1)
Space Complexity: O(1)

7. Using the Command Line to Check for Leap Year in Java

Let's look at how to use the command line to check leap year:

Pseudocode

Start
Check if exactly one command-line argument is provided:
	If not, exit and show an error message.
Convert the command-line argument from a string to an integer and store it in year.
Check if year is a leap year using the following conditions:
	If year is divisible by 4, continue checking:
	If year is also divisible by 100, continue checking:
	If year is divisible by 400, print "year is a Leap Year".
	Otherwise, print "year is Not a Leap Year".
	Otherwise, print "year is a Leap Year".
	Otherwise, print "year is Not a Leap Year".
End

Code

public class Main {
    public static void main(String[] args) {
        // Check if the correct number of arguments is provided
        if (args.length != 1) {
        	System.out.println("Please provide exactly one year as a command-line argument.");
        	return;
        }

        // Parse the year from the command-line argument
        int year = Integer.parseInt(args[0]);

        // Check if the year is a leap year
        if (year % 4 == 0) {
        	if (year % 100 == 0) {
            	if (year % 400 == 0) {
                	System.out.println(year + " is a Leap Year");
            	} else {
                	System.out.println(year + " is Not a Leap Year");
            	}
            } else {
            	System.out.println(year + " is a Leap Year");
        	}
        } else {
        	System.out.println(year + " is Not a Leap Year");
        }
    }
}

How the code works

  1. Argument Check: The program first checks if exactly one command-line argument (year) is provided. If not, it pauses and shows an error message.

  2. Parse the Year: If one argument is provided, it converts that argument (which is a string) to an integer (year) using Integer.parseInt().

  3. Leap Year Check:

    • The program then checks if the year is divisible by 4 using the modulo operator %
    • If the year is divisible by 4, it checks if it's a century year (divisible by 100)
    • If it is divisible by 100, the program checks if the year is divisible by 400. If true, it prints "Leap Year"; otherwise, it is "Not a Leap Year"
    • If the year is not divisible by 100 but by 4, it prints "Leap Year"
  4. Final Output: If the year does not meet the criteria for a leap year (not divisible by 4), it prints "Not a Leap Year"

Output

2024 is a Leap Year

Complexity

Time Complexity: O(1)
Space Complexity: O(1)

Quick Recap: Comparison Table of Leap Year Implementation Methods in Java

Method How It Works Input Type Best For Why Choose It
If–Else Statements Uses step-by-step checks (divisible by 4 → 100 → 400) Hardcoded or Scanner Beginners, logic building Builds strong fundamentals; clearly shows leap-year rules
Ternary Operator Compresses all conditions into one expression Scanner or hardcoded Competitive programming, short code Very concise; reduces nesting
Boolean Method Uses a separate reusable isLeapYear(year) method Scanner or hardcoded Clean modular programs Makes the code reusable and organized
Scanner-Based Program Reads the year dynamically using Scanner User input Assignments, lab programs Ideal for interactive Java programs
Without Scanner Uses a hardcoded year value Hardcoded Quick testing, demos Fastest when input isn't needed
Built-in isLeap() Method Uses Year.of(year).isLeap() or GregorianCalendar Scanner or CLI Production-level applications Automatically handles edge cases; modern Java approach
Command-Line Arguments Accepts year via command-line argument CLI argument Automation scripts, dev tools Useful for terminal-based utilities and batch processing

Finding Leap Years Within a Range 2025 to 2225

Here's a program to find all the leap years between 2025 and 2225. It uses a for loop to iterate through the years and a helper function to check if a year is a leap year based on the rules of leap year divisibility discussed in the beginning.

Pseudocode

Start
Define two integer variables:
	startYear = 2025‍
	endYear = 2225
Print a message that displays leap years between startYear and endYear.
Loop through all years from startYear to endYear:
	For each year, check if the year is a leap year using isLeapYear(year):
	Proceed to verify if the year is divisible by four:
	Proceed to verify if the year is also divisible by 100:
	Return true (leap year) if the year is divisible by 400.
	Return false (not a leap year) else.
	Otherwise, return true (leap year).
	Otherwise, return false (not a leap year).
	If the function returns true, print year.
End

Code

public class Main {
    public static void main(String[] args) {
    	int startYear = 2025;
    	int endYear = 2225;

    	System.out.println("Leap years between " + startYear + " and " + endYear + ":");

    	for (int year = startYear; year <= endYear; year++) {
        	if (isLeapYear(year)) {
            	System.out.print(year + " ");
        	}
    	}
    }

    // Method to check if a year is a leap year
    public static boolean isLeapYear(int year) {
    	if (year % 4 == 0) {
        	if (year % 100 == 0) {
            	return year % 400 == 0;
        	}
        	return true;
    	}
        return false;
    }
}

How the code works

  1. The program defines a starting year as 2025 and an ending year as 2225

  2. It prints a message indicating that it will list all leap years within this range

  3. A for loop iterates through each year from 2025 to 2225

  4. For every year, determine if the year is divisible by 4:

    • If divisible by 4, it then checks if the year is divisible by 100:
      • If divisible by 100, it further checks if it is divisible by 400:
        • If divisible by 400, the year is a leap year and is printed
        • Otherwise, it is not a leap year and is skipped
      • If not divisible by 100, the year is a leap year and is printed
    • If not divisible by 4, the year is not a leap year and is skipped
  5. The program continues this process every year in the range and prints all leap years

Output

Leap years between 2025 and 2225:
2028 2032 2036 2040 2044 2048 2052 2056 2060 2064 2068 2072 2076 2080 2084 2088 2092 2096 2104 2108 2112 2116 2120 2124 2128 2132 2136 2140 2144 2148 2152 2156 2160 2164 2168 2172 2176 2180 2184 2188 2192 2196 2204 2208 2212 2216 2220 2224
=== Code Execution Successful ===

Complexity

Time Complexity: O(N) where N is the number of years in the range
Space Complexity: O(1)

Note

This range-based method is a powerful way to test your logic against multiple edge cases at once. When you loop through several centuries, you naturally encounter tricky years like 2100 (not a leap year) and 2000 (a leap year), making your program far more reliable.

This is also a great exercise for students preparing for coding tests, where range-based date questions often appear.

Edge Cases and Special Considerations

When implementing leap year checks, here are a couple of unique cases to keep in mind that might be problematic when getting incorrect input to check for leap years accurately.

1. Negative Years and Years Before the Gregorian Calendar System

2. Non-integer Input

3. Zero and Invalid Year Values

4. Century Years (Years Divisible by 100)

5. Large or Out-of-Range Year Values

6. Input Handling and Flag Dealing

Why This Matters

You can be more certain that your leap year software will function properly for all real-world-valid inputs and gracefully handle any incorrect, odd, or illogical inputs when you manage rules and exceptions for edge circumstances. This is valuable because it makes your work accessible to real-world applications of time, date, and calendar tools and makes it useful and user-friendly.

Conclusion

A leap year program may seem simple, but it quietly strengthens your core Java skills: conditional logic, clean syntax, handling edge cases, and using built-in libraries. Each method you explored, from basic if–else to Year.of(year).isLeap(), builds a different layer of thinking and helps you understand how real-world rules translate into code.

Remember, great programmers don't just write code; they model real problems into logical solutions. Mastering leap year logic is one of the best first steps in that journey.

If you're serious about growing your programming skills with structured guidance and real projects, the CCBP 4.0 Academy is the perfect place to start. Keep learning, keep experimenting, and keep building.

Frequently Asked Questions

1. What exactly is a leap year and why does it exist?

February has 29 days in a leap year, which is a year having 366 days. It exists to keep the calendar aligned with Earth's orbit, which takes approximately 365.2425 days. Without adjusting for leap years, our calendar would slowly drift away from actual seasons.

2. What is the rule to check whether a year is a leap year or not?

A year is a leap year or not based on this logic:

This is the same logic used in most calendar-related applications and programming solutions.

3. Why does the output differ across online compilers for the same leap year program?

Different compilers sometimes use various acm-java-libraries or internal runtime environments, which may change input handling or formatting but not the core logic. The leap-year calculation itself always remains consistent.

4. Which Java package is typically used for date or leap year detection?

The java.util package is commonly used, especially the Calendar or GregorianCalendar class, to check leap years. These classes simplify leap year detection without manually coding conditions.

5. Can I write my own leap year logic manually without Java date libraries?

Yes. A simple public class leapyear with basic conditional statements is enough. Many beginners start by writing the logic using if-else conditions before learning library-based approaches.

6. Are there any facts about leap year that beginners often get wrong?

Common misconceptions include:

These rules are essential for accurate leap-year programs.

7. How are leap year programs used in real applications?

They appear in calendar-related applications, age calculators, deadlines, scheduling apps, time-based simulations, banking interest calculations, and anywhere date accuracy matters.

8. Why do some IDEs require importing additional libraries?

Some online IDEs or platforms use custom acm-java-libraries for input/output support. Standard Java programs only require java.util when using built-in date classes.

9. Is there a difference between using logical operators vs. library methods for leap year detection?

10. What should a beginner remember when writing the leap year program?

Focus on:

Doing this will give you reliable results in both examination and practical/coding assessments.


Related Articles


Contact Information

NxtWave

Quick Links

Course Offerings