Java program to check if the given year is a leap year or not. Step by step Java leap year code explanation with proper output. The code implementation uses-
- Java if-else
- Java operator
What is a Leap year?
A year with 366 days is called a leap year. Leap year comes after every four years.
Two Rules to check whether a year is a leap year or not
- Year must be divisible by 4.
- If the year is a century, it must be divisible by 400.
For example, 1900 is divisible by 4 but it is not a leap year. As 1900 is a century it must be divisible by 400 to be a leap year.
Therefore, 1900 is not a leap year.
Java Leap Year Program Example
Q)Write a Java program to prompt the user to input a year and check if it’s a leap year or not.
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int year=0;
System.out.println("Enter Year");
year=sc.nextInt();
boolean leapYear=false;
if(year%4==0)
{
if(year%100==0)//checking if year is a century year or not
{
if(year%400==0)//century year must be divisible by 400 to be a leap year
leapYear=true;
else
leapYear=false;
}
else
leapYear=true;//any non-century year divisible by 4 is leap year
}
if(leapYear)
System.out.println(year+" is a leap year");
else
System.out.println(year+" is not a leap year");
}
}
Output 1
Enter Year
1900
1900 is not a leap year
Output 2
Enter Year
2020
2020 is a leap year
Code Explanation:
1.Taking input and assigning variables(line-2 to line-10)
- Creating class leap year(line-2)
- Taking the year as input from the user using scanner class(line-8)
- Assigning variable LeapYear to false initially(line-10).
booleanleapYear=false;
2.Checking rules for leap year(line-11 to line-22)
- Checking the main condition, if the year is divisible by 4 or not
if(year%4==0)
(line-11). - Also, whether year is a century or not.
if(year%100==0)
(line-13). - Finally, checking if the century year is divisible by 400 or not.
if(year%400==0)
(line-15)
3.Printing results(line-24 to line-27)
- If the above-mentioned conditions satisfy, the year is a leap year.
if(leapYear)
- Else the year entered is not a leap year.
In conclusion, We hope this tutorial helped you learn and understand how to code leap year program java in a simple way. Keep learning keep sharing. Follow us on Facebook and Instagram.