Check Leap Year in Java.

In this article, we are going learn how to check if the given year is a leap year or not using Java Programming and we will use Java if-else condition to solve this problem.

Leap Year are those Year in which we have 366 days whereas a normal Year contains 365 days. In leap year, the month Feburary contain 29 days. (alert-success)


Algorithm for Leap Year.

Below algorithm used to check if a year is a leap year or not:

  • Take an input year from the user.
  • If the year is evenly divisible by 4, go to step 3. Otherwise, go to step 6.
  • If the year is evenly divisible by 100, go to step 4. Otherwise, go to step 5.
  • If the year is evenly divisible by 400, go to step 5. Otherwise, go to step 6.
  • The year is a leap year (it has 366 days).
  • The year is not a leap year (it has 365 days).


Java Code Implementation to Find Leap Year.

import java.util.Scanner;

public class LeapYear {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int year;
        
        // Prompt user to enter a year
        System.out.print("Enter a year: ");
        year = input.nextInt();
        
        // Check if the entered year is a leap year
        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 1:
Enter a year: 2020
2020 is a leap year

Output 1:
Enter a year: 2022
2020 is not a leap year

In the above code, a year is a leap year if it is divisible by 4 but not divisible by 100, or if it is divisible by 400. This algorithm is based on the rules of the Gregorian calendar, which is the calendar system used in most of the world today.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS