Search code examples
javavariablesdeclarationampersand

What does an ampersand mean when assigning a variable? (Java)


What does the ampersand mean in this code?

int clothes = (random.nextInt(0x1000000) & 0x7f7f7f);

Solution

  • It's the bitwise AND operator.

    It operates on each bit position independently; the output bit in position n is only 1 if both the corresponding input bits in position n are also 1.

    In this context, the 0x7f7f7f is being used as a bit-mask. By having certain bit positions as 0, it means that the corresponding bit positions in clothes will always be 0. All other bit positions will take on the same value as produced by random.nextInt(0x1000000).