Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 isLeapYear implementation. What logical operator means?

Tags:

java

java-8

I am looking into the java 8 implemenetions of Date API and found this

Checks if the year is a leap year, according to the ISO proleptic calendar system rules.

This method applies the current rules for leap years across the whole time-line. In general, a year is a leap year if it is divisible by four without remainder. However, years divisible by 100, are not leap years, with the exception of years divisible by 400 which are.

For example, 1904 is a leap year it is divisible by 4. 1900 was not a leap year as it is divisible by 100, however 2000 was a leap year as it is divisible by 400.

The calculation is proleptic - applying the same rules into the far future and far past. This is historically inaccurate, but is correct for the ISO-8601 standard.

public boolean isLeapYear(long prolepticYear) {
        return ((prolepticYear & 3) == 0) && ((prolepticYear % 100) != 0 || (prolepticYear % 400) == 0);
    } 

But give us prolepticYear & 3.

11111001111
    &
00000000011
00000000011

what means prolepticYear & 3.

like image 942
Xelian Avatar asked Dec 12 '25 05:12

Xelian


1 Answers

prolepticYear & 3 let's put it slightly different. 3 in binary is 11. Thus prolepticYear & 11 would be zero only when last two bits from prolepticYear are zeroes. (that's actually called a bit mask).

And now think a bit different too:

 0100 - (4 in decimal, has last two bits zero)
 1000 - (8 in decimal, has last two bits zero)
 1100 - (12 in decimal, has last two bits zero)

 ... these are numbers divisible by four

Usually the & operation is faster then %.

Sometimes & is used for other purposes too (% operation may yield negative numbers, while & will not - that's how a bucket inside a HashMap is chosen based on possibly negative values of Key#hashcode, but not the case here)

like image 103
Eugene Avatar answered Dec 14 '25 18:12

Eugene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!