top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Java Leap Year Program

Introduction 

The Java leap year program is a simple yet important exercise for beginner-level programmers. It involves applying conditional statements to determine whether a given year is a leap year. 

Overview

Understanding leap year logic is crucial for building foundational programming skills involving conditionals, arithmetic operations, and logical operators. 

This tutorial will cover the logic behind leap years and guide you through the step-by-step implementation of a Java leap year program.

Introduction to Java Leap Year Program 

A Java leap year program determines whether a given year is a leap year. A leap year is a year that can be divided by 4 evenly, except for years that can be divided by 100 but not by 400. 

The program typically takes an input year, performs the necessary calculations or checks, and shows whether the year is a leap year. It is a basic example of using conditional statements and arithmetic operations in Java to solve a specific problem related to date and time.

Method 1: Using if-else Statements for Finding Leap Year in Java

The if-else statements allow us to evaluate multiple conditions and execute the appropriate code block based on the results. This approach provides a clear and straightforward way to determine leap years.

public class upGradTutorials {
    public static void main(String[] args) {
        int year = 2024;

        // Checking if the year is a leap year using if-else statements
        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");
        }
    }
}

In this example, we use a series of nested if-else statements to determine whether a given year is a leap year. First, we declare a variable year and assign it the value 2024.

Then, we check the conditions for a leap year using if-else statements:

  • If the year is divisible by 4, we proceed to the next level of checking.

  • If the year is divisible by 100, we check if it is also divisible by 400.

  • If the year is divisible by 400, it is a leap year. Otherwise, it is not.

  • If the year is not divisible by 100, it is a leap year.

Finally, we use System.out.println() statements to display the result, stating whether the year is a leap year.

Method 2: Using the Ternary Operator for Finding Leap Year

The ternary operator provides a concise way to assign a value based on a condition conditionally. It simplifies the code and makes it more readable by avoiding nested if-else statements.

Like the previous example, we first declare a variable year and assign it the value 2024 in this example.

Then, we use the ternary operator to check the conditions for a leap year:

  • The year is divisible by 4 and either not divisible by 100 or divisible by 400.

The result of the ternary operator is stored in the string variable leapYearStatus, which will be assigned either "Leap Year" or "Not a Leap Year" based on the conditions. Finally, we use a System.out.println() statement to display the result, stating whether the year is a leap year.

Method 3: Using Methods to Find Leap Year in Java

Using methods lets us encapsulate the logic for determining leap years into a reusable and modular code. This promotes code reusability and maintainability.

We will use the same logic for determining leap years as the first method (first example with if-else Statements). The difference lies in how the code is structured and expressed, offering different styles and levels of abstraction. 

public class upGradTutorials {
    public static void main(String[] args) {
        int year = 2024;

        // Checking if the year is a leap year using a method
        boolean isLeapYear = isLeapYear(year);

        // Displaying the result
        System.out.println(year + " is " + (isLeapYear ? "a leap year" : "not a leap year"));
    }

    public static boolean isLeapYear(int year) {
        if (year % 4 == 0) {
            if (year % 100 == 0) {
                if (year % 400 == 0) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
}

In the above program example, we define a method isLeapYear() that takes an integer parameter year and returns a boolean value indicating whether the year is a leap year or not.

Inside the isLeapYear() method, we use a series of nested if-else statements to check the conditions for a leap year, similar to Method 1. If the conditions are satisfied, we return true; otherwise, we return false.

In the main() method, we declare a variable year and assign it the value 2024. We then call the isLeapYear() method, passing the year as an argument. The result is stored in the boolean variable isLeapYear. Finally, we use a System.out.println() statement to display the result, stating whether the year is a leap year.

Method 4: Using the Command Line to Check for Leap Year in Java

Using the command line input allows for dynamic checking of leap years based on user input. It provides flexibility and interactivity to the program.

import java.util.Scanner;

public class upGradTutorials {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a year: ");
        int year = scanner.nextInt();
        scanner.close();

        // Checking if the year is a leap year using if-else statements
        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");
        }
    }
}

In this program, we use the command line to input a year and check if it is a leap year.

We use the Scanner class to read input from the command line. We prompt the user to enter a year and store it in the variable year.

Then, we use a series of nested if-else statements to determine if the year is a leap year, as explained in Method 1. Finally, we use System.out.println() statements to display the result, stating whether the year is a leap year.

Java Leap Year Program example to Find if a Given Year is a Leap Year  

Without Using Scanner Class

In this program, a fixed year value of 2024 is assigned to the variable year. The program uses a series of nested if-else statements to determine if the year is a leap year.

  • The first condition, year % 4 == 0, checks if the year is divisible by 4 without a remainder. If it is true, we proceed to the next condition.

  • The second condition, year % 100 == 0, checks if the year is divisible by 100 without a remainder. If it is true, we proceed to the next condition.

  • The third condition, year % 400 == 0, checks if the year is divisible by 400 without a remainder. If it is true, it means the year is divisible by 400, hence a leap year. We print the message that the year is a leap year.

Using Scanner Class

This program uses the Scanner class to take user input for the year. The user is prompted to enter a year using the System.out.print() statement.

We create a Scanner object named scanner to read the input from the console. We use scanner.nextInt() to read an integer value entered by the user and assign it to the variable year.

After reading the input, we call scanner.close() to release the resources associated with the Scanner object. This leap year program in Java using scanner follows the same logic as the previous program to determine if the entered year is a leap year. 

Using In-built isLeap() Method

import java.time.Year;

public class upGradTutorials {
    public static void main(String[] args) {
        int year = 2024;
        
        // Using in-built isLeap() method to check if the year is a leap year
        boolean isLeapYear = Year.of(year).isLeap();


        // Displaying the result
        if (isLeapYear) {
            System.out.println(year + " is a leap year");
        } else {
            System.out.println(year + " is not a leap year");
        }
    }
}

This program uses the in-built isLeap() method from the java.time.Year class to check if the year is a leap year. We pass the year value (2024) to the Year.of() method, which returns a Year object. Then, we call the isLeap() method on the Year object to get a boolean value indicating if the year is a leap year.

Based on the result, we use an if-else statement to print the appropriate message stating whether the year is a leap year. Note: The isLeap() method internally follows the same logic described in the earlier methods to determine if the year is a leap year.

Rules to Verify 

To verify the correctness of a Java Leap Year program, you can follow these rules:

  • Divisible by 4: A leap year can be divided by 4.

  • Not divisible by 100: If a year can be divided by 100, it is not a leap year unless it is also divisible by 400.

  • Divisible by 400: If a year can be divided by 400, it is always a leap year.

By applying these rules, you can ensure that the program correctly identifies leap years.

To further verify the program, you can test it with various inputs, including leap and non-leap years, and compare the output against the expected results. Additionally, consider edge cases such as negative years or years beyond the range of valid years to ensure the program handles them gracefully.

Implementation: Finding Leap Years Within a Range

public class upGradTutorials {
    public static void main(String[] args) {
        int startYear = 2000;
        int endYear = 2023;

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

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

    public static boolean isLeapYear(int year) {
        if (year % 4 == 0) {
            if (year % 100 == 0) {
                if (year % 400 == 0) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
}

In this leap year program in Java using for loop, we find the leap years within a given range specified by the variables startYear and endYear. We assume the range is from 2000 to 2023. 

We use a for loop to iterate through each year within the range. We call the isLeapYear() method for each year to check if it is a leap year. The isLeapYear() method follows the same logic as explained in the previous examples to determine whether a year is a leap year. This leap year program in Java using if else returns true if the year is a leap year and false otherwise. 

If a leap year is within the range, we print it using the System.out.println() statement.

Implementation: Using Strings for Finding the Range

public class upGradTutorials {
    public static void main(String[] args) {
        String startYearString = "2000";
        String endYearString = "2023";

        int startYear = Integer.parseInt(startYearString);
        int endYear = Integer.parseInt(endYearString);

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

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

      public static boolean isLeapYear(int year) {
        if (year % 4 == 0) {
            if (year % 100 == 0) {
                if (year % 400 == 0) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
}

Like the Java leap year program (for loop technique), we use two string variables in this program, startYearString and endYearString while assuming the range is from "2000" to "2023".

We convert the string values to integers using the Integer.parseInt() method and assign them to the variables startYear and endYear.

The rest of the program follows the logic explained in the previous example. We iterate through each year within the range, call the isLeapYear() method to check if it is a leap year, and print the leap years using the System.out.println() statement.

Conclusion 

This tutorial explored the Java leap year program, delving into the underlying logic and its significance for beginner-level programmers. Armed with this knowledge, can handle similar programming challenges confidently and further expand your skills in Java. You can also consider taking up a comprehensive technical course offered by upGrad to hone your programming skills.

FAQs

1. Can we write a leap year program in JavaScript?

Yes, we can write a JavaScript program to determine whether a given year is a leap year. We can use conditional statements and the modulo operator (%) to check for divisibility.

2. What is a century leap year program in Java?

A century leap year program in Java is a program that determines if a given year, typically a multiple of 100, is a leap year according to the leap year rules.

3. How can you find the leap year in array Java?

To find the leap year in an array in Java, iterate through the array elements and apply the leap year logic to check whether each year is a leap year.

Leave a Reply

Your email address will not be published. Required fields are marked *