Decision Making
Java provides several control structures for making decisions: if, if-else, if-else if-else, switch, and switch expression (Java 14+). These structures allow a program to evaluate conditions and execute different code blocks based on the evaluation result.
The switch expression is a modern feature that is more compact and safer than the traditional switch statement. Using -> as the arrow syntax, switch expressions do not require a break in every case (preventing fall-through bugs). The yield keyword allows a switch expression to return a value. Java 21 even supports pattern matching in switch to check an object's type.
Decision Structures:
- if — run the block if the condition is true
- if-else — pick one of two blocks
- if-else if-else — pick from several conditions
- switch — pick from several constant values
- switch expression — modern, no fall-through
Code Example
public class DecisionMaking {
public static void main(String[] args) {
int score = 85;
// if-else if-else
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: D");
}
// Switch expression (Java 14+)
String day = "MONDAY";
String type = switch (day) {
case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> "Workday";
case "SATURDAY", "SUNDAY" -> "Weekend";
default -> "Unknown";
};
System.out.println(day + " is a " + type);
}
}
Code Explanation
The if-else if-else block evaluates conditions from top to bottom. As soon as the first true condition is found, the associated block is executed and the rest are ignored. If none are true, the else block is executed. A switch expression uses the arrow syntax ->, which automatically breaks after each case (no manual break is needed, unlike the old switch statement). default is the fallback case when nothing matches.
Everyday Example
A store discount program based on the shopping total:
public class StoreDiscount {
public static void main(String[] args) {
int totalSpent = 250000;
double discount;
if (totalSpent >= 500000) {
discount = 20;
} else if (totalSpent >= 200000) {
discount = 10;
} else if (totalSpent >= 100000) {
discount = 5;
} else {
discount = 0;
}
double discountAmount = totalSpent * discount / 100;
int finalTotal = (int) (totalSpent - discountAmount);
System.out.println("Total spent: $" + totalSpent);
System.out.println("Discount: " + discount + "%");
System.out.println("Final total: $" + finalTotal);
}
}
Summary
Decision making is the core of every interactive program. Java offers flexibility with if-else for complex conditions and switch for value-based choices. Use switch expressions for cleaner, safer code in modern Java.