Here we are explaining how to write a java program to check whether a year is a leap year or not. So first we have to know what is a leap year and how we can check a year is a leap year or not.
To understand this example, you should have knowledge of the following Java programming topics
A normal year has 365 days. Leap year is a year that has 366 days. Mostly it occurs every four years. If a year has February 29, then that year is a leap year.
Example:2020
Example:2000
So we have to declare the class LYear with a public modifier. Then read the year from the user and save it into the variable yr. Then by using the if statement
checks if yr % 4 equals zero or not. If zero then also check yr % 100 equals zero and yr % 400 equals zero. If both of these conditions are true set flag=true.Else set flag=false.If yr % 4 equals zero and yr % 100 does not equal zero then we have to set flag=true else set flag=false. Then we have to check the flag value. If the flag equals true then we will display the year as a leap year. If the flag equals false then we will display the year is not a leap year.
STEP 1: Declare the class LYear with public modifier
STEP 2: Open the main() to start the program, Java program execution starts with the main()
STEP 3: Declare the variable yr as integer and flag as boolean. And initialize the value of the flag to false.
STEP 4: Read the year from the user into the variable yr using a scanner.
STEP 5: check if
yr % 4 equals zero, if true then do step 6. Else
do step 8.
STEP 6: Check if
yr % 100 equals zero or not. If it's not zero then the set flag equals true.
STEP 7: If yr % 100 equals zero then check if yr % 400 equals zero, if true then set flag equals true, else set flag equals false. And go to step 9.
STEP 8: If yr % 4 is not equal to zero then set flag=false.
STEP 9: If the flag equals true then display the year as a leap year. Else display the year is not a leap year.
import java.util.Scanner;
public class LYear {
public static void main(String[] args) {
int yr;
boolean flag = false;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the year : ");//Read the Year from the user.
yr = sc.nextInt();
if(yr % 4 == 0)
{
if( yr % 100 == 0)
{
// if the year is divisible by 400 then it is leap year.
if ( yr % 400 == 0)
flag = true;
else
flag = false;
}
else
flag = true;
}
else
flag = false;
if(flag==true)
System.out.println("It is a leap year!");
else
System.out.println("It is not a leap year!");
}
}
Enter the year : 2000 2000 is a leap year! Enter the year : 2001 2001 is not a leap year!