2.1 Relational and Logical Operators
Programs do not only run statements in order. They often need to check whether a condition holds, then choose what to do next. In Java, a condition’s result is a boolean: either true or false.
Relational operators
Relational operators compare two values. The result is true or false, not another number.
Common Java relational operators:
<: less than
>: greater than
<=: less than or equal to
>=: greater than or equal to
==: equal to
!=: not equal to
Important: one equals sign = means assignment. Two equals signs == mean comparison.
int age = 17;
System.out.println(age < 18); // true
System.out.println(age == 18); // false
System.out.println(age != 18); // trueage = 17 stores 17 in the variable age. age == 18 checks whether the current value of age equals 18.
Logical operators
Logical operators combine multiple boolean conditions. Their result is still true or false.
&&: the whole expression is true only when every condition is true.
||: the whole expression is true when at least one condition is true.
!: turns true into false, and false into true.
Truth tables
A truth table lists every possible input combination to make the rules clear.
&& is true only when both sides are true.
| A | B | A && B |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
|| is true when at least one side is true.
| A | B | A `\ | \ | ` B |
|---|---|---|---|---|
| true | true | true | ||
| true | false | true | ||
| false | true | true | ||
| false | false | false |
! acts on a single value and flips the result.
| A | ! A |
|---|---|
| true | false |
| false | true |
int age = 20;
boolean hasTicket = true;
System.out.println(age >= 18 && hasTicket); // true
System.out.println(age < 18 || hasTicket); // true
System.out.println(!hasTicket); // falseIt helps to read conditions like plain language: age >= 18 && hasTicket means “the age is at least 18, and the person has a ticket.”
Combining conditions
Unlike math notation, Java does not support chaining comparisons. 0 < age < 18 is a compile error, so write it as two conditions joined by &&.
int age = 16;
System.out.println(0 < age && age < 18); // trueWhen a condition becomes complex, name each smaller condition first, then combine them.
int score = 85;
int attendance = 92;
boolean passed = score >= 60 && attendance >= 80;
boolean excellent = score >= 90 || attendance >= 95;
System.out.println(passed); // true
System.out.println(excellent); // falseDo not rush to squeeze every condition into one line. Naming smaller conditions makes the program easier to read and debug.