Logical
Logical expressions are combinations of relational expressions.
A logical expression compares two true/false values and results in a single true/false value.
Logical Operators¶
| Name | Operator | Example | Evaluates to true when... |
|---|---|---|---|
| AND | && |
a && b |
both a and b are true |
| OR | || |
a || b |
either a or b is true |
| AND1 | & |
a & b |
both a and b are true |
| OR1 | | |
a | b |
either a or b is true |
[1] we rarely use this operator
&& - AND¶
Both of the AND operator's operands must be true for the logical expression to evaluate to true.
boolean maleOlderThan65 = sex == 'M' && age > 65;
|| - OR¶
If either of the OR operator's operands are true, the expression will evaluate to true.
boolean lessThan18orGreaterThan65 = age < 18 || age > 65;
Practice Exercise¶
Each side of a logical expression must evaluate to a boolean result. The example below would generate a compiler error.
int age = 21;
boolean isRegistered = true;
boolean isRegisteredAnd21 = isRegistered && age = 21; //error
&& mistakenly uses the = operator, which results in a number. We cannot compare boolean && int. This code will not compile.
Drill¶
Expressions/src/drills/Logical.java
* Add code to check if the salary is in the range of min and max and assign that value to isExpectedSalary.
* Add code to check and output whether the salary is "dreamy," where dreamy means it is more than $10,000 greater than your max.
* Add code to check and output whether the salary is "laughable," where laughable means it is at least $5,000 less than your minimum salary requirement.