In this article, we will understand how to check if the given year is a leap year. This is accomplished by checking if the given year is divisible by 4 and 100.
A leap year contains one additional day that is added to keep the calendar year synchronized with the astronomical year. A year that is divisible by 4 is known as a leap year. However, years divisible by 100 are not leap years while those divisible by 400 are.
Below is a demonstration of the same −
Input
Suppose our input is −
Enter a year: 2000
Output
The desired output would be −
2000 is a Leap year
Algorithm
Step 1 - START Step 2 - Declare an integer values namely my_input and a Boolean value isLeap, Step 3 - Read the required values from the user/ define the values Step 4 - Check if the given year is divisible by 4 and 100 using an if-else condition Step 5 - Display the result Step 6 - Stop
Example 1
Here, the input is being entered by the user based on a prompt. You can try this example live in our coding ground tool
.
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
int my_input;
boolean isLeap = false;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.print("Enter the year : ");
my_input = my_scanner.nextInt();
if (my_input % 4 == 0) {
if (my_input % 100 == 0) {
if (my_input % 400 == 0)
isLeap = true;
else
isLeap = false;
}
else
isLeap = true;
}
else
isLeap = false;
if (isLeap)
System.out.println(my_input + " is a Leap year");
else
System.out.println(my_input + " is not a Leap year");
}
}Output
Required packages have been imported A reader object has been defined Enter the year : 2000 2000 is a Leap year
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
public class LeapYear {
public static void main(String[] args) {
int my_input = 2000;
boolean isLeap = false;
System.out.println("The year is defined as " +my_input);
if (my_input % 4 == 0) {
if (my_input % 100 == 0) {
if (my_input % 400 == 0)
isLeap = true;
else
isLeap = false;
}
else
isLeap = true;
}
else
isLeap = false;
if (isLeap)
System.out.println(my_input + " is a Leap year");
else
System.out.println(my_input + " is not a Leap year");
}
}Output
The year is defined as 2000 2000 a Leap year