java & operator with two integers?

29.7k views Asked by At

From what I understand the & operator is similar to the && operator except that the && only checks the second if the first is true, while the & checks both regardless of the result of the first one. Basically the && just saves a little time and power.

If that is so, then how does this code work?

int l = 0;
if ((l & 8) != 0 && (l & 4) == 0){ do something}

what does the (l & 8) and the (l & 4) do? What does the & do in this case?

1

There are 1 answers

2
Raffaele Rossi On

& and && are two different operators but the difference is not what you've described.

& does the bit-wise AND of two integers and produces a third integer whose bit are set to 1 if both corresponding bits in the two source integers are both set to 1; 0 otherwise.

&& applies only to two booleans and returns a third boolean which will be true if both the input booleans are true; false otherwise.