How it works the & Operator with numbers? For example:
x = 8 & 4;
and the answer is 0.
How can i find the answer without using java or any other program?
How it works the & Operator with numbers? For example:
x = 8 & 4;
and the answer is 0.
How can i find the answer without using java or any other program?
Java has three kinds of "AND" operators - the logical one, which is &&
, a bitwise one, which is &
, and a &
on boolean
s, which does not short-circuit. Java compiler can distinguish between the kinds of operators by examining the type of the operands.
Bitwise operator takes binary representations of its operand, performs "AND" on each bit, and returns the result as a number.
For 4 and 8, bitwise "and" is zero, because they do not have 1
bits in common:
00000100 -- 8
00001000 -- 4
--------
& 00000000 -- 0
For other numbers, say, 22 and 5, the result would be different:
00010110 -- 22
00000101 -- 5
--------
& 00000100 -- 4
You can find the answer without using Java converting the numbers into binary format:
4 = 0100
8 = 1000
If you perform an AND operation on each bit, you get:
0 & 1 = 0
1 & 0 = 0
0 & 0 = 0
0 & 0 = 0
That's why it's zero.
& is a bitwise and operator ... the binary values of 8 and 4 are
8 = 1000
4 = 0100
if you know how AND operator works then you know that
1 & 0 = 0;
so after a bitwise AND, there will be all 0