How does Java handle arguments separated by | ?
for example
private void foo(int i) {
System.out.println(i);
}
private void bar() {
foo(1 | 2 | 1);
}
Which would give the output
3
I’ve seen this used in SWT/JFace widget constructors. What I can’t figure out is how the value of i is decided.
The
|is a bitwise or-operator.means call foo with the argument 1 bitwise-or 2 bitwise-or 1.
1in binary is012in binary is10Bitwise or of
01and10is11which is 3 in decimal.Note that the
|operator can be used for booleans as well. Difference from the||operator being that the second operand is evaluated even if the first operand evaluates totrue.Actually, all bitwise operators work on booleans as well, including the xor
^. Here however, there are no corresponding logical operator. (It would be redundant, since there is no way of doing a “lazy” evaluation of^🙂