views:

109

answers:

2

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.

+7  A: 

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 ^ :)

aioobe
+1 for "second operand is evaluated even if the first operand evaluates to true", didn't know that.
f1sh
+2  A: 

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.

krock
`1 | 2 = 2` ..?
aioobe
@aioobe, thanks fixed
krock