This may seem like a very noobish question, but I'v seen comparing symbols such as: | ! &
outside of If Statements and have been wondering what it means, and how to use it. Most what I'v seen is setting variable such as int = 1 | 2
. Thankyou.

- 164
- 1
- 13
-
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html – Alexis C. Dec 27 '13 at 08:53
-
http://en.wikipedia.org/wiki/Bitwise_operation – Mysticial Dec 27 '13 at 08:53
-
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html – René Link Dec 27 '13 at 08:54
-
are u confusing `|` and `||`? `|` means a `bitwise-or` operation, and `||` is a logic or – shengy Dec 27 '13 at 08:56
-
@shengy Not true. `|` is logic or (applied to boolean operands), `||` is *conditional* logic or. – Marko Topolnik Dec 27 '13 at 09:27
-
Thanks for all the helpful links, I know it was a lame question, but I am still a leaning programmer, hints me coming to a community of helpful programmers willing to answer questions. – 8bitslime Dec 27 '13 at 09:32
-
@MarkoTopolnik Thanks~ my fault. Thought it was same in `C` – shengy Dec 27 '13 at 12:48
2 Answers
They do exactly what they do inside if
. Assuming a and b are both of type boolean
:
a | b
is true iffa
orb
is true (or both).a & b
is true iffa
andb
are both true.- !a is true iff a is false.
I suspect what's confusing you is the notion that expressions of type boolean
can be treated as values just like int
and float
. There's nothing magical happening here, though. boolean
is a type just like int
and float
. You can have boolean
variables, boolean
parameters, boolean
fields and functions that return boolean
.
Also note that, with boolean arguments, you are more likely to encounter ||
and &&
than |
and &
. They are roughly the same, but exhibit short-circuit behaviour. For example, when evaluating the expression f() || g()
, if f()
returns true, the whole expression will evaluate to true and g()
won't even be called since it won't affect the answer. This is faster if g()
is slow, but also changes the meaning of the program if g()
would have had side effects (like changing global state or printing to the console). In contrast, f() | g()
evaluates g()
no matter what f()
returns.

- 181,030
- 38
- 327
- 365
Heard of bitwise operators? Yes they are the same.
Refer : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

- 66,731
- 38
- 279
- 289