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

## All 9 Replies

``````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.

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
``````
commented: Makes it cristalclear! +14
``````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`?

ok got it, thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.