In this tutorial, we are going to learn writing java program to check if the given year is a leap year or not.
A Leap year comes every 4 year and the days in February month will have 29 days. Basically one extra days added in February month that making a year 366 days. And rest year which is not a leap contains 365 days.
Technically the year number is divided by four if it is not the century is a leap year. And if the year is a century, must be divisible by 400 to become a leap year.
Let’s see an Example
- 2004, 2008, 2012 are the leap year because it is divided by 4 and are not a century.
- 2000 is the leap year because it is divisible by 400 but 1900 is not because it is not divisible by 400. Here we are dividing by 400 because they are a century.
Leap Year Program in Java
import java.util.*;
public class Main {
public static void main(String[] args) {
int year;
System.out.println("Java Program to Check Year is leap or not" );
Scanner sc = new Scanner(System.in);
System.out.println("Please give the Year");
year= sc.nextInt();
if (year % 400 == 0) {
System.out.println("Given year "+ year +" is a leap year.");
} else if (year % 100 == 0) {
System.out.println("Given year "+ year +" is not a leap year.");
} else if (year % 4 == 0) {
System.out.println("Given year "+ year +" is a leap year.");
} else {
System.out.println("Given year "+ year +" is not a leap year.");
}
}
}
Output
Java Program to Check Year is leap or not
Please give the Year
2021
Given year 2021 is not a leap year.
Explanation
For the input year 2021, the year 2021 is the not a factor of 400 or 100 or 4, so the remainder when 2021 is divisible by 400or 100 or 4, will never be 0. Hence the year 1900 is not a leap year.