Posted By

joshnunn on 09/10/09


Tagged

year test java method leap


Versions (?)

isLeapYear


 / Published in: Java
 

  1. public boolean isLeapYear(){
  2. boolean leapYear;
  3. int divideByFour = year % 4;
  4. int divideBy100 = year % 100;
  5. int divideBy400 = year % 400;
  6. if (divideBy400 == 0){
  7. leapYear = true;
  8. } else if (divideBy100 == 0){
  9. leapYear = false;
  10. } else if (divideByFour == 0){
  11. leapYear = true;
  12. } else {
  13. leapYear = false;
  14. }
  15. return leapYear;
  16. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: DannyB on September 14, 2009

Here is what I use:

public static boolean isLeapYear( int year ) {
    if( (year % 4) != 0 ) return false;

    if( (year % 100) != 0 ) return true;

    return (year % 400) == 0;
}

Why perform the mod by 100 and divide by 400 every time. Most years never need those mod operations performed. Then, why test for mod by 400 first, when seldom does this test need to be performed. Ditto mod by 100. For almost all years, the mod by 4 test must be performed, so let's do it first, and skip the other mod operations and conditional tests most of the time. Not only is it more efficient, this function is simpler source code, and probably simpler object code too.

I put both functions in a for loop from 1 to 3000 and got identical results.

Posted By: joshnunn on September 17, 2009

Thanks for the alternate code. You're absolutely right about cutting out a lot of unneccessary stuff.

Thanks for helping out a n00b!

You need to login to post a comment.