Boolean Operators
Estimated time to read: 2 minutes
Boolean comparison cheat sheet¶
x | y | NOT !x | AND x&y | OR x|y | XOR x^y * |
---|---|---|---|---|---|
true | true | false | true | true | false |
true | false | false | false | true | true |
false | true | true | false | true | true |
false | false | true | false | false | false |
*XOR - If one of them is true, it is true. If neither is true, it is false. If both true, it says they are false
Short Cut Operators¶
&& and | | are 'short circuit' operators These short cut operators do quick checks. With &&
(AND), if the left hand side is false, Java will not evaluate the right hand side. With ||
(OR), will not evaluate the right hand side if the left hand side is true
&
and |
do not short circuit. They are rarely used for logical operations.
&
, |
and ^
applied to integral variables are performed bitwise
Boolean Operator Examples¶
The boolean operators can be used to combine relational expressions.
Basic boolean comparison example¶
The above states, if X
is less than 8 and y
is less than 10, then execute the code in the code block.
Boolean variable example¶
A boolean variable is assigned to the result of the expression. Is x
less than 8, in this instance it is, so it returns true as a short circuit operator is in use. Note! If x
was greater than 8, then the code would run against y
, as it is an OR statement. The variable b
is set to true
.