Java Program to Check given Year is Leap Year or Not
This topic demonstrates about how to programatically find out the given year is leap year or not using java program.
What is Leap Year?
- A leap year is a calendar year containing one additional day.
- The normal year has total 365 days but, the leap year has 366 days.
- The extra day is added in leap year in the month of february which has 29 days instead of the normal 28 days.
- Leap years occur every 4 years.
Example - 2020 is a leap year and then 2024.
Example - Program for checking entered year is leap or not using java program
Steps
- Accept the input year from user
- compare the given input year using if else statement
- check if year is divisible by 4 or not. if not then display it is not leap year
- if yes then again check year is divisible by 100 or not. if not then display it is leap year.
- if yes then again check the year is divisible by 400 or not. if not then display it not leap year.
- if yes then display it is leap year.
Program
import java.util.Scanner;
public class LeapYearEx
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int year;
System.out.print("Enter year : ");
year = scan.nextInt();
if(year % 100 == 0)
{
if(year % 400 == 0)
{
System.out.print(year+" is a leap year");
}
else
{
System.out.print(year+" is Not leap year");
}
}
else if (year % 4 == 0)
{
System.out.print(year+" is a leap year");
}
else
{
System.out.print(year+" is Not leap year");
}
}
}
Output
Enter year : 2024
2024 is a leap year
Example - Find all leap years from given range of years
import java.util.Scanner;
public class LeapYearEx
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int startYear,endYear,year;
System.out.print("Enter starting and ending year: ");
startYear = scan.nextInt();
endYear = scan.nextInt();
for(int i=startYear;i<=endYear;i++)
{
year = i;
if(year % 100 == 0)
{
if(year % 400 ==0)
{
System.out.println(year+" is a leap year");
}
}
else if (year % 4 == 0)
{
System.out.println(year+" is a leap year");
}
}
}
}
Output
Enter starting and ending year: 2000 2020
2000 is a leap year
2004 is a leap year
2008 is a leap year
2012 is a leap year
2016 is a leap year
2020 is a leap year