Java Program to Test if a Year is Leap Year or not
A leap year is a calendar year also known as an intercalary year or bissextile year. It contains an additional day to keep the calendar year synchronized with the seasonal year. In this tutorial, we will write a Java program that will read a year from the user and the program will determine whenever it is a leap year or not.
During a leap year, the year competes in 366 days instead of regular 365 days by extending the February month 28 days to 29 days.
Algorithm of leap year findings
Use the following basic formula to find out if a year is leap year or not;
if (the year is not divisible by 4 ) then (it is a common year)
else if (the year is not divisible by 100 ) then (it is a leap year)
else if (the year is not divisible by 400) then (it is a common year)
else ( it is a leap year)
It is that simple;
Java Program: Test if a Year is Leap Year or Not
import java.util.Scanner;
/**
*
* Java program to test a year is leap year or not
* @author Mehrab Mohul
*/
public class LeapYear {
void leap_year() {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
if ( year % 4 != 0 ) {
System.out.println("The year " + year + " is not a leap year");
} else if ( year % 100 != 0 ){
System.out.println("The year " + year + " is a leap year");
} else if ( year % 400 != 0 ){
System.out.println("The year " + year + " is not a leap year");
} else {
System.out.println("The year " + year + " is a leap year");
}
}
public static void main(String[] args) {
LeapYear obj = new LeapYear();
obj.leap_year();
}
}
Output
Sample Input | Sample Output |
---|---|
Enter a year: 2000 Enter a year: 2005 |
The year 2000 is a leap year The year 2005 is not a leap year |
Java Program Explanations
- In the above java problem, the first requirement is to read integer year value from the user. So we import the Scanner function from java utility library at the very first line of code.
- Then we have declared a Java public class called
LeapYear
and under the class, we have created a methodleap_year()
. We have used the simple java conditionals to implement the algorithm for finding leap years in the method. - We also printed the message if an input year is a leap year or not in the method.
- Finally, int the main method we have created an object called
obj
to revoke or execute or call the method.