In computer science, it’s very important when writing code to be able to express a few key ideas. In Java, :
- A AND B (only true if both are true) is &&
- A OR B (only false if both are false) is ||
- NOT A (the opposite; true becomes false, false becomes true) is !
They all look reasonably similar to what you’d expect, but
just like = is not to check for equality (that’s ==, since = is for assigning,
and the single = can’t mean both), they are slightly different from what you
might have first thought, for a very similar reason. (We’ll cover what single-&
and single | mean in Java much later.)
In Java, you can AND booleans or Boolean expressions with &&, as in A
&& B; you can OR them with ||, as in X || Y; and you can NOT them by !,
as in !isEmpty().
You can, of course, connect them into much longer chains: A AND
(B OR C) AND NOT D OR (E AND F) would look like
A && (B || C) && !D || (E && F), and
so on. Depending on the values of A..F, this will change the value of the whole
expression.
Notice in this example the use of parentheses to force ordering, just as in
math.
In exactly the same sense as we have PEMDAS/BODMAS in math, logical operations
also have an order of precedence: parentheses go first, then ==, then ! (NOT),
then && (AND), then || (OR).
No comments:
Post a Comment