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.
foo(1 | 2 | 1);
means call foo with the argument 1 bitwise-or 2 bitwise-or 1.
1
in binary is 01
2
in binary is 10
Bitwise or of 01
and 10
is 11
which 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 to true
.
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 ^
:)
it is using the bitwise OR operator. For starters, 1 | 1 = 1
so the second 1 is redundant. If we remove the redundant 1 we are left with the equation 1 | 2 = 3
. Looking at it in 2 bit binary it looks like:
01 | 10 = 11
The or operator will match up the corresponding bits from each or the values and if there is one 1 in either or both values for a given position, the result is a 1. If both values for both the corresponding bits then the result is 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With