Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Java handle arguments separated by |?

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.

like image 483
Ozsie Avatar asked Jul 08 '10 10:07

Ozsie


2 Answers

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

like image 174
aioobe Avatar answered Sep 28 '22 08:09

aioobe


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.

like image 30
krock Avatar answered Sep 28 '22 07:09

krock