Logical Operators
Java supports three logical operators :
Operator | Description |
---|---|
&& | Logical AND |
|| | Logical OR |
! | Logical NOT |
Logical AND(&&)
The logical AND (&&)
operator creates logical expressions where both values must be true for the overall expression to also be true.
If either value is false, the overall expression will also be false. If the first value is false, the second value won’t be evaluated, because it can’t possibly make the overall expression equate to true. This is known as short-circuit evaluation.
Logical AND(&&) Example
isAllowed will evaluate to true since both operands are true. (true && true) is true.
boolean enteredDoorCode = true;
boolean passedRetinaScan = true;
boolean isAllowed = ( enteredDoorCode && passedRetinaScan );
isAllowed will be false after evaluating the expression. The reason is because one of the operands is false.
boolean enteredDoorCode = true;
boolean passedRetinaScan = false;
boolean isAllowed = ( enteredDoorCode && passedRetinaScan );
Logical OR (||)
The logical OR (||)
operator is an infix operator made from two adjacent pipe characters. You use it to create logical expressions in which only one of the two values has to be true for the overall expression to be true.
Example - Logical OR (||)
The canPass
will evaluate to true since one of the operands evaluates to true.
boolean hasDoorKey = false;
boolean knowsOverridePassword = true;
boolean canPass = ( enteredDoorCode && passedRetinaScan );
Logical Not(!)
The logical NOT operator (!
) inverts a Boolean value so that true becomes false, and false becomes true.
It is a prefix operator, and appears immediately before the value it operates on, without any white space.
Example - Logical Not(!)
boolean isAllowed = false;
isAllowed = !isAllowed; //Now we are allowed. isAllowed becomes true