# How to Check Whether a Year is Leap Year in Java

Usually there are 365 days in a year. However once every four years, there are 366 days in year. This year is called leap year and on a leap year, February has 29 days. However not all years divisible by 4 are leap years. Following are the rules to determine whether a year is leap year or NOT,

• A leap year is evenly divisible by 4
• An year evenly divisible by 4 is NOT a leap year if it is also evenly divisible by 100, UNLESS it is also evenly divisible by 400. Note that an year evenly divisible by 400 is always a leap year since it is also evenly divisible by 4.

The following Java program uses the above rules to find out whether a given year is leap year or not.

```
import java.util.Scanner;

/**
* The following program checks whether a given year is a leap year.
* Takes the input year from command line.
*/
public class LeapYear {

public static void main(String[] args) {

LeapYear ly = new LeapYear();
Scanner sn = new Scanner(System.in);
int year = sn.nextInt();

if(ly.isLeapYear(year)) {
System.out.println("Year "+year+" is a leap year");
}else {
System.out.println("Year "+year+" is NOT a leap year");
}
}

/**
* An year is leap year if it satisfies the following 3 criteria,
* 1. Divisible by 4
* 2. If it is divisible by 4 and 100 it is NOT leap year unless it is
* also divisible by 400. Since an year divisible by 400 is also divisible
* by 4 and 100, you can just check for 400 in code.
* @param year
* @return
*/
private boolean isLeapYear(int year) {
if((year%4==0 && year%100!=0) || year%400==0) {
return true;
}else {
return false;
}
}
}```

Another way to find whether a year is leap year is to find out whether the year has 366 days. This can be easily achieved using Calendar API in Java. The following example shows how Java calendar API can be used to check for leap year,

```
import java.util.Calendar;
import java.util.Scanner;

/**
* The following program checks whether a given year is a leap year.
* Takes the input year from command line.
*/
public class LeapYear2 {

public static void main(String[] args) {

LeapYear2 ly = new LeapYear2();
Scanner sn = new Scanner(System.in);
int year = sn.nextInt();

if(ly.isLeapYear(year)) {
System.out.println("Year "+year+" is a leap year");
}else {
System.out.println("Year "+year+" is NOT a leap year");
}
}

/**
* A leap year has 366 days and we use Java calendar API
* to check whether given year has more than 365 days!
* @param year
* @return
*/
private boolean isLeapYear(int year) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
return c.getActualMaximum(c.DAY_OF_YEAR) > 365;
}
}```

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.