I\'ve seen many instances where |
or &
are used, but I haven\'t understood what they are used for. I know what &&
and ||<
&
and |
are bitwise operators that is they compare the bit representation(binary value).
`&` -bitwise AND operator
`|` -bitwise OR operator
&&
and ||
are used to compare the actual values in case of primitives like int,double,etc.
and the address in case of objects.They are called logical operators.
1. Lets go to an example to make it simpler (bitwise operator):
int p=9; int q=10;
//binary representation of 9 and 10 are 1001 and 1010 respectively.
Now, p & q
returns a one in each bit position for which the
corresponding bits of both operands are ones.
p|q
returns a one in each bit position for which the corresponding bits of either or both operands are ones.
2.An example for logical operators.
int p=9; int q=10;
p>0 && q>0
returns true since p
and q
are both greater than 0
(since the conditions on either side of the operator is true).
p>0 || q<0
returns true since at least one condition is true(here,p is greater than 0).
I hope that this has helped you to understand the difference between bitwise
and logical
operators.