0

Possible Duplicate:
Shortcut “or-assignment” (|=) operator in Java

I found the following example code in the Android SDK docs:

    boolean retValue = false;
    retValue |= mActionBarHelper.onCreateOptionsMenu(menu);
    retValue |= super.onCreateOptionsMenu(menu);

Can anyone show me equivalent code, to demonstrate what this does?

Note: I assume the method calls return a boolean value, so I like to see an example what this looks like as an if-else construct.

Community
  • 1
  • 1
mrd
  • 4,561
  • 10
  • 54
  • 92
  • 1
    @GregKopff: It *is* a bitwise OR, not a logical OR. – Makoto May 10 '12 at 21:34
  • @Makoto: I didn't think there was a defined bit representation of a boolean data type. – Greg Kopff May 10 '12 at 21:38
  • @GregKopff: A bitwise OR means that you're taking two sets of bits, and keeping the bits set high if and only if the bit in the same place is set high. Example: 1001 | 0110 = 1111. [Check Wikipedia for more info.](http://en.wikipedia.org/wiki/Bitwise_operation#OR) – Makoto May 10 '12 at 21:40
  • @Makoto: Well understood - and for bytes, chars, shorts, ints and longs that have a defined bit representation, that makes sense. Sure a boolean can be considered 1 bit (the language uses a byte to store it), but it doesn't have a bit representation in the same way the other data types do. You can't cast a boolean to a byte and get 0x00 / 0x01 out. Yes, a bitwise operation is easy enough to conceptualise on a single bit - but for the reasons above, I'm "surprised" by it. – Greg Kopff May 10 '12 at 21:48

2 Answers2

8

| applied to a boolean is just a simple boolean OR.

boolean retValue = false;
retValue = retValue | mActionBarHelper.onCreateOptionsMenu(menu);
retValue = retValue | super.onCreateOptionsMenu(menu);
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
2

Shorthand for or with myself and assign to me, though it is non-short circuit or instead of logical or. As it is available as a short version of assigning and or:ing sometimes used anyway with booleans, as there is no ||=. But important note: in this case it will call both methods even though retValue might already be true

So equivalent (logic wise) statements can be several, but some would be:

boolean a = mActionBarHelper.onCreateOptionsMenu(menu);
boolean b = super.onCreateOptionsMenu(menu);
boolean retValue =  a || b;

or

boolean retValue = mActionBarHelper.onCreateOptionsMenu(menu);
retValue = super.onCreateOptionsMenu(menu) || retValue;
Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49