Hi all, I was reading a few things on the net about how to calculate a leap year in java (and not only for that matter). So something like ...if( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) )...

So on wikipedia I have found that:

if year is divisible by 400 then
   is_leap_year
else if year is divisible by 100 then
   not_leap_year
else if year is divisible by 4 then
   is_leap_year
else
   not_leap_year

so what's that year % 4 == 0 about? the above if should only say if( year % 400 == 0 && year % 100 != 0 ) ) because if these 2 conditions are satisfied then the year is leap year
Or am I getting it wrong?
thanks

As found on GOOGLE

public static boolean isLeapYear(int year) {
    assert year >= 1583; // not valid before this date.
    return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}

so what's that year % 4 == 0 about? the above if should only say if( year % 400 == 0 && year % 100 != 0 ) ) because if these 2 conditions are satisfied then the year is leap year
Or am I getting it wrong?

Yes, you're getting it wrong! A year is a leap year if it's divisible by 4 ( ie year % 4 == 0), with special cases for years divisble by 100 or 400. If you dont have the year % 4 == 0 then your answer is correct for the special cases, but not for the basic ordinary case.

Edited 3 Years Ago by JamesCherrill

The year 2012 was a leap year as will be the year 2016. Both years are not divisible by 100 or 400.

ah ok, sorry this is getting more confusing. Wikipedia above said that if a year is divisible by 100 then it's not a leap year hence the year % 100 != 0 condition, so if ((the year is divisible by 4) and (not by 100) or (it is divisible by 400)) then it's a leap year.

extra () for absolute clarity...
if ( ( (the year is divisible by 4) and (not by 100) ) or (it is divisible by 400) ) then it's a leap year

... or maybe this is clearer still:

boolean isLeapYear(year)
   if year divisible by 400 return true
   if year divisible by 100 return false
   if year divisible by 4 return true
   return false
Comments
Makes it cristalclear!
boolean isLeapYear(year)
   if year divisible by 400 return true
   if year divisible by 100 return false
   if year divisible by 4 return true
   return false

Ok, why is it returning false at the very end?

Ok, why is it returning false at the very end?

Because most years are not leap years. For example, what would isLeapYear(2013) return if not false?

This article has been dead for over six months. Start a new discussion instead.