🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

WAP to check for leap year in Java  


Logical Steps:
  • To check the leap year, follow these steps:
    1. Take a year variable.
    2. Apply the leap year conditions:
      • A year is a leap year if:
        • It is divisible by 400, OR
        • It is divisible by 4 but NOT divisible by 100.
    3. Use an if-else statement for the condition:
      • If the above conditions are true, the year is a leap year.
      • Otherwise, it is not a leap year.
    4. Print the result.
Program:
  • Below is the simple program:
    public class CheckLeapYear
    {
        public static void main(String[] args)
        {
            int year = 2025;
    
            // Check if the year is a leap year using conditional logic
            if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
            {
                System.out.println(year + " is a leap year.");
            }
            else
            {
                System.out.println(year + " is not a leap year.");
            }
        }
    }
    Output:
    2025 is not a leap year.
  • Below is the program by taking user input:
    import java.util.Scanner;
    
    public class CheckLeapYear
    {
        public static void main(String[] args)
        {
            // Import Scanner Class to take user input
            Scanner scanner = new Scanner(System.in);
    
            // Take input from the user
            System.out.print("Enter a year: ");
            int year = scanner.nextInt();
    
            // Check if the year is a leap year using conditional logic
            if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
            {
                System.out.println(year + " is a leap year.");
            }
            else
            {
                System.out.println(year + " is not a leap year.");
            }
    
            // Close the scanner to release resources
            scanner.close();
        }
    }
    Output:
    Enter a year: 2024
    2024 is a leap year.
Program Explanation:
  • Import Scanner Class:
    • The Scanner class is imported to take user input.
  • Declare a Variable:
    • An integer variable (year) is declared to store the user’s input.
  • Take Input:
    • The program prompts the user to enter an integer, and scanner.nextInt() reads the input and stores it in the year variable.
  • Leap Year Logic:
    • The if condition checks two scenarios:
      • If the year is divisible by 400, it is a leap year.
      • If the year is divisible by 4 but NOT divisible by 100, it is also a leap year.
    • If neither condition is true, the year is not a leap year.
  • Display the Result:
    • The program prints whether the given year is a leap year or not.
  • Close Scanner:
    • The scanner.close() method is used to close the input stream and release resources.