Recently I came across a code snippet in a book which sets a Boolean value to a field like this
the input identifier is a List of Strings
if (identifier.size() >= 2) {
int c = Integer.parseInt(identifier.get(1));
bulk = (c & 4) == 4;
hazardous = (c & 2) == 2;
toxic = (c & 1) == 1;
}
what is the need for unary & operators here?Can’t this be done using a simple
c==4 etc instead of (c & 4)== 4 ?
No, this is a bitwise operation.
Imagine
c=7. In that case all conditions would be true.In binary, you’d have this:
Due to bitwise AND (&) you get
0111 & 0010 = 0010etc.