Java Program to Check Leap year

Java Program To Check Leap year

Here is a Java Program to check Leap year, A leap year has 366 days, instead of 365. To check whether a year is a leap year or not first we have to find out the possible ways of checking a leap year mathematically. The following conditions have to be fulfilled:

  1. The year is a leap year if it has 366 days.
  2. It is not if it has 365 days.
  3. The year is evenly divisible by 400, then check for step 1, else move to step 2.
  4. If it is evenly divisible by 100, check for step 3, else move to step 1.
  5. The year is evenly divided by 4, check for step 4, else move to step 2.

Steps to Check Leap Year

  • Take an integer variable as input for the year.
  • Assign a particular value to the variable.
  • We first check if the year is divisible by 4, but not 100, simply print the output as The year is a leap year.
  • If the input is completely divisible by 400, simply print the same output.
  • Else, we print β€˜The year is not a leap year’.

How to Check Leap Year by Giving Input

import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
int year;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a year to check if it is a leap year:");
year = scan.nextInt();
scan.close();
boolean Leap = false;
if(year % 4 == 0)
{
if( year % 100 == 0)
{
if ( year % 400 == 0)
Leap = true;
else
Leap = false;
}
else
Leap = true;
}
else {
Leap = false;
}
if(Leap==true)
System.out.println(year + " is a Leap Year.");
else
System.out.println(year + " is not a Leap Year.");
}
}

Learn Scanner Class in Java

The output of the program will be:

Enter a year to check if it is a leap year: 2020
2020 is a leap year

Check Leap Year

This is the whole elaborated version of how to understand the algorithm. To reduce the complexity of the program, we can also write is as following:

public class DeveloperHelps {
public static void main(String[] args)
{
//year to leap year or not
int year = 2020;
System.out.println();        
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");
System.out.println();
}
}

The output of the program will be:

2020 is a leap year.

Thanks for the reading post. I hope you like and understand the post. If you have any doubts regarding this post please comment below.

Leave a comment

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