Determine if a Year is a Leap Year in Java

Java provides an easy mechanism to determine if a specific year is a leap year. This Java tutorial shows how you how.

To determine if a year is a leap year, you first need to create an instance of a GregorianCalendar. Once you have an instance, you can ask if a specific year is leap year. The following is an example:

//Create a calendar
GregorianCalendar calendar = new GregorianCalendar();

//Determine if a year is a leap year
boolean isLeapYear = calendar.isLeapYear(2008);

In our next example, we show how to determine if the current year is a leap year.
//Create a calendar
GregorianCalendar calendar = new GregorianCalendar();

//Determine if the current year is a leap year
int currentYear = calendar.get(Calendar.YEAR);
boolean isLeapYear = calendar.isLeapYear(currentYear);


0 comments:

Post a Comment