4.1.1.2, 4.1.1.4, 4.1.1.5 - Selection and Boolean conditions (Java)
Build precise comparisons and combined conditions, then choose and nest Java branches without losing boundary cases.
Java route status: incomplete: runnable support pending. This lesson uses written code answers.
Relational comparisons
A comparison produces a Boolean value that a selection statement can use to choose an action.
| Meaning | Java operator | Example |
|---|---|---|
| Equal to | == | score == 10 |
| Not equal to | != | score != 10 |
| Less than | < | score < 10 |
| Greater than | > | score > 10 |
| Less than or equal to | <= | score <= 10 |
| Greater than or equal to | >= | score >= 10 |
score = 10 assigns a value; score == 10 tests a value. Java comparisons do not chain mathematically: write score >= 0 && score <= 10, not 0 <= score <= 10. For string contents use .equals, rather than reference comparison with ==.
int score = 10;
if (score >= 10) {
System.out.println("Pass");
} else {
System.out.println("Retry");
}
The condition is tested once. Exactly one branch runs and then execution resumes after the whole if statement. Here the output is Pass; >= includes the boundary. Replacing it by > would make the boundary score fail. Use braces even for a short body so adding a statement later does not accidentally put it outside the branch.
Boolean conditions
Boolean operators combine conditions according to their truth values.
Boolean condition
An expression whose result is either true or false and can control selection or iteration.
Java uses ! for NOT, && for AND, || for OR and ^ for Boolean XOR. NOT reverses one truth value. AND is true only when both operands are true. OR includes the case where both are true. XOR is true only when exactly one is true.
| A | B | A AND B | A OR B | A XOR B |
|---|---|---|---|---|
| false | false | false | false | false |
| false | true | false | true | true |
| true | false | false | true | true |
| true | true | true | true | false |
For example, entry may require a valid ticket AND NOT a cancellation: validTicket && !cancelled. A discount for either a member or a child uses member || child; using XOR would wrongly exclude a child who is also a member. XOR fits a rule requiring exactly one of two options.
! binds more tightly than &&, which binds more tightly than ||; parentheses express the intended grouping. !(a && b) differs from !a && b. && and || short-circuit: Java evaluates the second operand only when it is needed. Thus name != null && name.length() > 0 safely avoids calling a method on null. Boolean ^ evaluates both operands. Use these distinctions deliberately rather than relying on accidental evaluation order.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account