Search code examples
javaconventions

Preference for "==0" vs. "<1"


I've written a method in Java to determine whether a given year is a leap year or not. Here's the method as written:

public static boolean isLeapYear (int year) {
        return year <= 9999 && year > 0 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

However, I noticed that IntelliJ originally corrected my redundant logic by replacing all of the instances of "== 0" with "< 1". I've since changed them back to "==0" in the above example.

Is there some preference for one over the other in terms of code simplicity or clarity? It seems like the simpler version is the "equals 0" as it is more precise than simply "less than 1."

Not sure if there's some convention on this, or if there's a reason why you'd prefer to use <1 over ==0 in any given case.

Thanks!


Solution

  • Clarity is your guiding principle here: Go with == 0 and != 0.

    The two options are effectively interchangeable, because in your case the remainder can't be less than zero, however == 0 and != 0 are easier to read, and much closer to their natural langauge meaning of "has a remainder of zero" etc, and moreover it is the industry convention.

    There is no "performance" difference.