Java 8 implementation isLeapYear. What does boolean operator mean?

I am researching java 8 implementation of Date API and found this

Checks if the year is a leap year, according to the ISO proprietary calendar system rule.

This method applies the current rules for leap years throughout the chart. In general, a year is a leap year if it is divisible by four without a remainder. However, years divisible by 100 do not jump years, except for years divisible by 400.

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

The calculation will fail - the application of the same rules in the distant future and the distant past. This is historically inaccurate, but true for the ISO-8601 standard.

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

      

But give us prolepticYear and 3.

11111001111
    &
00000000011
00000000011

      

which means "proleptic" and 3.

+3


source to share


2 answers


prolepticYear & 3

let it be a little different. 3

in binary format 11

. Thus, prolepticYear

and 11

will be equal to zero only when the last two bits of prolepticYear

are equal to zero. (which is actually called a bit mask).

Now think a little differently:

 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 than %

.

Sometimes &

also used for other purposes (the %

operation can give negative numbers, &

it won't - how the bucket internally is selected HashMap

based on possible negative values Key#hashcode

, but not here)

+6


source


(prolepticYear & 3) == 0

checks if the two least significant bits are prolepticYear

0

.

This is equivalent to checking if it is divisible prolepticYear

by 4.

In other words,



(prolepticYear & 3) == 0

      

equivalent to

(prolepticYear % 4) == 0

      

+3


source







All Articles