Java Code for Calculating Leap Year: Comparing Two Approaches
Calculating leap years is a common coding exercise. Two approaches are often encountered: the one presented in "The Art and Science of Java" and the other commonly used solution.
Code from "The Art and Science of Java"
boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0));
This code checks if the year is divisible by 4 but not divisible by 100, or if it is divisible by 400. While this logic works, it is unnecessarily complex.
Improved Code
if ((year % 4 == 0) && year % 100 != 0) { println(year + " is a leap year."); } else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0)) { println(year + " is a leap year."); } else { println(year + " is not a leap year."); }
This improved code simplifies the logic by splitting it into two conditions: years divisible by 4 but not 100 are leap years, and years divisible by 400 are also leap years (despite being divisible by 100). This code is more readable and concise.
Alternative Solution
public static boolean isLeapYear(int year) { return year % 400 == 0 || (year % 100 != 0 && year % 4 == 0); }
This alternative solution combines the two separate conditions into a single more efficient expression. It is the most commonly used approach due to its simplicity and performance.
Which Code is the Best?
The improved code is the best choice, striking a balance between readability and efficiency. It is straightforward to understand and performs well for most leap year calculations. However, the alternative solution remains a valid option if performance is a primary concern.
The above is the detailed content of What\'s the Best Java Code for Determining Leap Years?. For more information, please follow other related articles on the PHP Chinese website!