Sub topic 1
Build Conditions That Evaluate to true or false
Build Conditions That Evaluate to true or false
A condition is a test that gives either true or false. In Java, boolean is the type that holds those two values. For example, score >= 70 is true when score is 85. The operator >= means “greater than or equal to.” To test whether two numbers are equal, use ==. A single = stores a value instead.
Logical operators let you combine or reverse conditions:
- && means “and.” Both conditions must be true.
- || means “or.” At least one condition must be true.
- ! means “not.” It flips true to false or false to true.
Java checks the left side of && and || first. If the left side of && is false, or the left side of || is true, Java skips the right side. This is called short-circuit evaluation. For example, in attempts != 0 && points / attempts >= 10, Java skips the division when attempts is zero. The operator != means “not equal to.”
Run One Block with if and else
A block is a group of statements inside braces, { and }. Put the condition for an if inside parentheses. If the condition is true, Java runs the if block. If it is false, Java runs the else block instead.
For example, you could test whether a score is at least 70. The if block could print “Pass,” while the else block could print “Keep practicing.” Leave out else if there is nothing to do when the test is false.
Test Multiple Conditions in the Right Order
Use else if to try another condition when the previous one is false. Save this program as Main.java and run it:
public class Main {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 70) {
System.out.println("Pass");
} else {
System.out.println("Keep practicing");
}
}
}At 85, the first test is false and the second is true, so the program prints “Pass.” Java stops at the first true condition. Check the higher cutoff first because a score of 95 meets both conditions.
Exercise
If you check score >= 70 first and score >= 90 second, what prints for a score of 95?
Show answer
Pass. The first test is true, so Java skips the second test.