-5

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.

8bitslime
  • 164
  • 1
  • 13

2 Answers2

4

They do exactly what they do inside if. Assuming a and b are both of type boolean:

  1. a | b is true iff a or b is true (or both).
  2. a & b is true iff a and b are both true.
  3. !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.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
0

Heard of bitwise operators? Yes they are the same.

Refer : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289