0

I have read that b1 |= b2 is the shortcut equivalent to b1 = b1 | b2. My question is really two-fold:

Isn't "=" an assignment operator rather than a comparison operator? If so, what does it do in this context?

Or, is it a comparison operator here and what scenario exists where you would need to compare a variable to itself (i.e. b1 = b1)?

(I realize this is probably the newbie-est newb question to ask, but I've only got informal experience writing bash scripts and no educational background in programming. Be kind. ;)

Note: this is in reference to the question here: Shortcut "or-assignment" (|=) operator in Java

Community
  • 1
  • 1
NenTenEn
  • 11
  • 2
  • 1
    `|=` isn't a compound comparison operator. – Andy Turner Feb 06 '17 at 12:31
  • 3
    There are no compound comparison operators, only compound assignment operators. – Eran Feb 06 '17 at 12:31
  • Is this a boolean thing where b1 will be true if either b1 or b2 is true? – NenTenEn Feb 06 '17 at 12:33
  • @BackSlash how do you think you could use a short-circuiting form of `|=`? I mean, suppose `||=` did exist, how would you use it in a meaningful way? – Andy Turner Feb 06 '17 at 12:36
  • @BackSlash That was the explanation I was looking for. Thank you! – NenTenEn Feb 06 '17 at 12:39
  • 2
    @BackSlash Wrong. The pipe operator `|` is used for both bitwise and logical OR. The double pipe operator is used only for logical, and the difference between `a | b` and `a || b` when the operators are boolean is that the first is not short-circuiting, and the second is. – RealSkeptic Feb 06 '17 at 12:39

1 Answers1

1

There are many operators in Java. But 'Compound comparison operator' is not one of them. You should read Java basics from a good book like 'Head first Java'.

To answer this particular question, b1 |= b2 is compound assignment.

  1. = assigns the the result of b1|b2 to LHS operand i.e b1.
  2. Since it is clear now that it is an assignment operator not comparison, the result of b1 |= b1 will be same as b1 = b1|b1.

(Note | here is the logical OR between two numbers not || which is a conditional operator. | and || have different meanings)

HTH.

madcap
  • 90
  • 7
  • Thanks for the clarification. Did you mean to write `b1 = b1|b2` rather than `b1 = b1|b1`? – NenTenEn Feb 06 '17 at 12:51
  • I meant `b1 = b1|b1`, in response to your second question where you had doubt about same variable being used on both sides. – madcap Feb 06 '17 at 18:20