Search code examples
javabitwise-operatorscomparison-operatorsbitwise-and

What's the purpose of & in Java?


So, I was following a pacman tutorial and the coder uses & not &&. He doesn't explain what it does though. I searched it up and it says that unlike &&, & checks both statements. That makes sense. But the coder doesn't use it in a comparison context. This is his code.

screenData[] is an 255 element int array.

int ch = 0, pos = 0;
if((ch & 16) != 0) {
      screenData[pos] = (int) (ch & 15);
    }

Please tell me why he did that and what's the use of & in this context.


Solution

  • The & operator used in the code is the bitwise AND operator. This operator checks the corresponding bits of the two operands at the bit level and generates its result.

    In the code snippet, the second bit (corresponding to 16) of the variable ch is checked using the ch & 16 expression. If the second bit is 1 (not 0), the last 4 bits of ch (the corresponding bits 15) are assigned to the screenData[pos] array. This usage is used to control certain bits of ch and act accordingly.

    For example, the expression ch & 16 is used to check the second bit of the variable ch, while the expression ch & 15 is used to get the last 4 bits of ch. Hence, the & operator is used to control or manipulate certain bits in bitwise operations.