Logical Operators Part 2
Part of the Fundamentals section of Coddy's Java journey — lesson 23 of 73.
Logical operators have a special table called "Truth table" that shows what the combination of logical operators returns.
Truth table for the and (&&) operator:
| a | b | a && b |
|---|---|---|
| false | false | false |
| false | true | false |
| true | false | false |
| true | true | true |
The only way to get a true for the and (&&) operator is if both a and b are true
Truth table for the or (||) operator:
| a | b | a || b |
|---|---|---|
| false | false | false |
| false | true | true |
| true | false | true |
| true | true | true |
In this case, to get a true result, either a or b should be true.
Truth table for the not (!) operator:
| a | !a |
|---|---|
| false | true |
| true | false |
Here the value of a is reversed. If a is false then !a is true
Challenge
BeginnerYou need to assign integer values to variables b1 and b2 so that b3 evaluates to true in the expression: b3 = !((b1 + b2) > (b1 * b2)).
Cheat sheet
Truth tables show the results of logical operator combinations:
AND operator (&&): Returns true only when both operands are true
| a | b | a && b |
|---|---|---|
| false | false | false |
| false | true | false |
| true | false | false |
| true | true | true |
OR operator (||): Returns true when either operand is true
| a | b | a || b |
|---|---|---|
| false | false | false |
| false | true | true |
| true | false | true |
| true | true | true |
NOT operator (!): Reverses the boolean value
| a | !a |
|---|---|
| false | true |
| true | false |
Try it yourself
public class Main {
public static void main(String[] args) {
// Type your code below
int b1 = ?
int b2 = ?
boolean b3 = !((b1 + b2) > (b1 * b2));
// Don\'t change the line below
System.out.println("b3 = " + b3);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else