Lesson 9 of 20
Conditional Statements
Make decisions with if, else if, else, and switch.
Learning objectives
- Write an
ifstatement from a Boolean condition. - Use
else iffor multiple ranges or alternatives. - Use
switchwhen selecting among discrete values. - Avoid overlapping or unreachable conditions.
- Build a grade classification program.
1. if statements
An if block runs only when its condition evaluates to true.
Example: pass or fail
int mark = 68;
if (mark >= 50) {
System.out.println("Pass");
}
2. if-else
Use else when exactly one of two branches should run.
int mark = 42;
if (mark >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
3. else-if chains
Order matters. Check the highest range first so a high score is not captured by a lower condition.
Example: grade classification
int mark = 83;
if (mark >= 80) {
System.out.println("Grade A");
} else if (mark >= 70) {
System.out.println("Grade B");
} else if (mark >= 60) {
System.out.println("Grade C");
} else if (mark >= 50) {
System.out.println("Grade D");
} else {
System.out.println("Grade F");
}
4. switch
switch is useful when a single value selects among known alternatives.
int menuChoice = 2;
switch (menuChoice) {
case 1 -> System.out.println("Add record");
case 2 -> System.out.println("Search record");
case 3 -> System.out.println("Exit");
default -> System.out.println("Invalid choice");
}
Mini project: shipping charge calculator
public class ShippingCalculator {
public static void main(String[] args) {
double orderTotal = 135.00;
boolean member = true;
double shipping;
if (orderTotal >= 150) {
shipping = 0;
} else if (member && orderTotal >= 100) {
shipping = 5;
} else {
shipping = 12;
}
System.out.printf("Order: RM %.2f%n", orderTotal);
System.out.printf("Shipping: RM %.2f%n", shipping);
System.out.printf("Final total: RM %.2f%n", orderTotal + shipping);
}
}
Common mistakes
| Problem | Why it happens | How to fix it |
|---|---|---|
| Conditions are in the wrong order | A broad condition matches before a specific one. | Test more specific or higher ranges first. |
| Missing braces in multi-line logic | Only one statement belongs to the branch. | Use braces consistently, especially while learning. |
Forgetting default in switch | Unexpected values are not handled. | Add a default branch when appropriate. |
Summary
Conditional statements make a program respond differently to different data. Lesson 10 introduces loops so the same logic can be repeated efficiently.