A leap year is a 366-day year, which is one day longer than a normal year. This additional day comes is in February, where February is 29 days compared to the usual 28 days. Leap year comes in an interval of four years.
A year is leap year if the below conditions are satisfied:
- Year is multiple of 400.
- Year is multiple of 4 and not multiple of 100.
Example – Check a year is a leap year or not
public class LeapYear { public static void isLeapYear(int year) { if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) { System.out.println("Year " + year + " is a leap year"); } else { System.out.println("Year " + year + " is not a leap year"); System.out.println(); } } public static void main(String[] args) { LeapYear.isLeapYear(2012); LeapYear.isLeapYear(2016); LeapYear.isLeapYear(2020); LeapYear.isLeapYear(2021); } }
Output
Year 2012 is a leap year Year 2016 is a leap year Year 2020 is a leap year Year 2021 is not a leap year
Example – Check a year is a leap year or not using Java library method
The calendar class has a utility method that returns the maximum number of days in a year that you can use to check if it is less than 365.
import java.util.Calendar; public class LeapYear { public static void isLeapYear(int year) { boolean result = false; Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); // setting year in to calendar int noOfDays = cal.getActualMaximum(Calendar.DAY_OF_YEAR); if (noOfDays > 365) { result = true; } if (result) { System.out.println("Year " + year + " is a leap year"); } else { System.out.println("Year " + year + " is not a leap year"); System.out.println(); } } public static void main(String[] args) { LeapYear.isLeapYear(2012); LeapYear.isLeapYear(2016); LeapYear.isLeapYear(2020); LeapYear.isLeapYear(2021); } }
Output
Year 2012 is a leap year Year 2016 is a leap year Year 2020 is a leap year Year 2021 is not a leap year