I know the rules for && but what is & and | how to evaluate? Please explain me with an example.
Those are bitwise operators. This should help:
http://www.ensta.fr/~diam/java/online/notes-java/data/expressions/bitops.html
Those are the bitwise AND and bitwise OR operators.
int a = 6; // 110
int b = 4; // 100
// Bitwise AND
int c = a & b;
// 110
// & 100
// -----
// 100
// Bitwise OR
int d = a | b;
// 110
// | 100
// -----
// 110
System.out.println(c); // 4
System.out.println(d); // 6
EDIT
Thanks to Carlos for pointing out the appropriate section in the Java Language Spec (15.22.1, 15.22.2) regarding the different behaviors of the operator based on its inputs.
Indeed when both inputs are boolean, the operators are considered the Boolean Logical Operators and behave similar to the Conditional-And (&&
) and Conditional-Or (||
) operators except for the fact that they don't short-circuit so while the following is safe:
if((a != null) && (a.something == 3)){
}
This is not:
if((a != null) & (a.something == 3)){
}
The operators && and || are short-circuiting, meaning they will not evaluate their right-hand expression if the value of the left-hand expression is enough to determine the result.
&
and |
are bitwise operators on integral types (e.g. int
): http://download.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
&&
and ||
operate on booleans only (and short-circuit, as other answers have already said).
& and | provide the same outcome as the && and || operators. The difference is that they always evaluate both sides of the expression where as && and || stop evaluating if the first condition is enough to determine the outcome.
Check out short circuiting.
&& and || won't check the second argument if the first argument is enough to work out the outcome.
E.g.
bool something = true;
bool anotherThing = false;
if (something && anotherThing)
//or
if (something || anotherThing)
in the above the anotherThing
variable will not be evaluated because something = true
so the overall evaluation is true.
When you use & or |, all arguments are evaluated, regardless if the overall result can be found from the first argument.
I think you're talking about the logical meaning of both operators, here you have a table-resume:
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 NOT
short-circuiting (x != 0) && (1/x > 1) SAFE
not short-circuiting (x != 0) & (1/x > 1) NOT SAFE