[Campbell]: BTW: Please write "boolean res = res1 || res2;" rather than using |.
I agree with this advice, but just to clarify: you should generally prefer || to | for an OR in boolean operations, e.g. in conditional expressions. This is not to be confused with the OR inside a regex, where | is what you need. Also in this particular example there is no real difference between | and ||, however in many other applications there is a difference. Generally you only want | if you're using integers, not booleans, and you want to perform bitwise operations like
If you want to operate on each bit individually like this, then | is what you want. But for boolean expressions with a single boolean result, || is clearer and also has the advantage of short-circuiting - not evaluating the second operand if it's not necessary. This is what you want probably 99% of the time, so it's good to get in the habit of writing || rather than |.
The same arguments would also apply to writing && rather than & for AND.
"I'm not back." - Bill Harding, Twister
Joined: Oct 13, 2005
Originally posted by Peter Heide: Thank you Richie.
You're welcome. And thank you, Jim for the explanation of || which I ought probably to have given myself.
Just a thought ... using | in boolean expressions is sometimes quite essential, especially when working with the Collections Framework. Think of this:
Then the outcome of
is quite different from the outcome of
basicallly because in the first way, t.add(b) is never touched unless Set s already contains Object a.
Joined: Jan 30, 2000
Guido: true. I rarely see code that uses | like that, and personally I would probably rewrite it (or insert a comment) in order to make it more obvious that using | wasn't just a typo. Just because people aren't used to seeing it, and someone may try to "fix" it later without realizing the true intent.
Joined: Dec 22, 2004
in productive code I'd surely add some comment. Plus, programming with such side effects isn't quite the style of code that is easy to read. Whole thing was just a thought ...