Home >Java >javaTutorial >What\'s the Best Way to Accurately Determine a Leap Year in Java?
In your original implementation, you correctly check if a year is divisible by 4 but not by 100. However, there is a minor issue with handling century years. To accurately determine if a century year is a leap year, you need to additionally check if it is divisible by 400. For instance, 1600 is a leap year, but 1800 is not.
The recommended implementation uses the Calendar class to determine if a year is a leap year. This class employs the Gregorian calendar system and provides an accurate and straightforward way to calculate leap years.
If accuracy and simplicity are your priorities, using the Calendar class is the ideal approach. It leverages the built-in capabilities of the Java platform to handle leap year calculations seamlessly.
If you prefer a more concise implementation, you can use the following code:
public static boolean isLeapYear(int year) { if (year % 4 != 0) { return false; } else if (year % 400 == 0) { return true; } else if (year % 100 == 0) { return false; } else { return true; } }
This code first checks if the year is divisible by 4 but not by 100. If either of these conditions is true, the year is immediately classified as non-leap or leap, respectively. Additionally, if the year is divisible by 100 but not by 400, it is also classified as non-leap.
The above is the detailed content of What\'s the Best Way to Accurately Determine a Leap Year in Java?. For more information, please follow other related articles on the PHP Chinese website!