Home > Java > javaTutorial > What\'s the Best Java Code for Determining Leap Years?

What\'s the Best Java Code for Determining Leap Years?

Barbara Streisand
Release: 2024-12-07 12:15:17
Original
937 people have browsed it

What's the Best Java Code for Determining Leap Years?

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));
Copy after login

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.");
}
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template