Boolean Expressions
| English | Chinese | Pinyin |
|---|---|---|
| Boolean expression | 布尔表达式 | bù ěr biǎo dá shì |
| relational operators | 关系运算符 | guān xì yùn suàn fú |
true or false
- A Boolean expression 布尔表达式 evaluates to exactly one of two values:
trueorfalse. - Conditions in
ifstatements and loops are Boolean expressions. - Store one in a
booleanvariable:boolean passed = score >= 60; - Everything in selection and repetition rests on these
true/falseresults.
Relational operators
- Relational operators 关系运算符 compare two values and give a Boolean:
<less than,<=at most,>greater than,>=at least.==equal to,!=not equal to.5 > 3istrue;4 == 5isfalse.
== versus =
==tests equality;=assigns — completely different jobs.x == 5asks "isxequal to5?" and givestrue/false.x = 5stores5inx.- Using
=where you meant==is a classic bug (and often a compile error in a condition).
Predicting the value
- To evaluate a Boolean expression, plug in the values and apply the operator.
- With
x = 7:x < 10→true;x == 7→true;x != 7→false. - Read the operator carefully —
<=includes equality,<does not. - Being able to predict the result is the core skill for tracing code.
== compares; = assigns — never confuse them in a condition. if (x = 5) is wrong (it assigns, not compares); you want if (x == 5). And mind the boundary operators: x <= 10 is true when x is exactly 10, but x < 10 is false — an off-by-one that flips many conditions.
With int age = 18;:
age >= 18→true(18 is at least 18).age > 18→false(18 is not greater than 18).age == 18→true;age != 20→true.
A Boolean expression evaluates to true or false, using relational operators < <= > >= == !=. Remember == tests equality while = assigns, and that <=/>= include the boundary but </> don't. Store a result in a boolean variable to reuse it.
A Boolean result
Boolean expressions evaluate to true (1) or false (0).
Which operator tests whether two values are equal?
== tests equality; = assigns.
With int age = 18;, the expression age > 18 is true.
18 is not greater than 18; age >= 18 would be true.
With int x = 7;, the expression x <= 7 is true.
<= includes equality, so 7 <= 7 is true.
What value does 5 != 5 evaluate to?
!= means 'not equal'; 5 is equal to 5, so it's false.
A variable that stores true or false has type ___ (one word).
boolean holds true/false.