What is the difference between & and && in Java?
& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false
(x != 0) & (1/x > 1)
<-- this means evaluate (x != 0)
then evaluate (1/x > 1)
then do the &. the problem is that for x=0 this will throw an exception.
(x != 0) && (1/x > 1)
<-- this means evaluate (x != 0)
and only if this is true then evaluate (1/x > 1)
so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1)
.
EDIT:
exprA | exprB
<-- this means evaluate exprA
then evaluate exprB
then do the |
.
exprA || exprB
<-- this means evaluate exprA
and only if this is false
then evaluate exprB
and do the ||
.
Besides not being a lazy evaluator by evaluating both operands, I think the main characteristics of bitwise operators compare each bytes of operands like in the following example:
int a = 4;int b = 7;System.out.println(a & b); // prints 4//meaning in an 32 bit system// 00000000 00000000 00000000 00000100// 00000000 00000000 00000000 00000111// ===================================// 00000000 00000000 00000000 00000100
boolean a, b;Operation Meaning Note--------- ------- ---- a && b logical AND short-circuiting a || b logical OR short-circuiting a & b boolean logical AND not short-circuiting a | b boolean logical OR not short-circuiting a ^ b boolean logical exclusive OR !a logical NOTshort-circuiting (x != 0) && (1/x > 1) SAFEnot short-circuiting (x != 0) & (1/x > 1) NOT SAFE