Conditionals (if-else & switch)
Conditionals control program branch paths based on boolean evaluations. Java supports standard if-else blocks, ternary evaluations, and modern switch expressions.
1 Compound Conditionals and Nested structures
Conditional logic uses relational variables to test conditions. If-else structures can be nested inside one another to construct complex flow routes.
2 Classic Switch vs. Modern Java 14+ Switch Expressions
Traditional switch statements use the `case` and `break` syntax. If you omit a `break`, execution falls through to the next case. Java 14 introduced modern Switch Expressions which use the arrow (`->`) syntax. This syntax is clean, prevents fall-through errors, and can return values directly.
Java — Conditionals and Switches
▶ Run Code
public class Main {
public static void main(String[] args) {
int score = 85;
// If-else structure
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: C or below");
}
// Ternary operator evaluation
String result = (score >= 50) ? "Passed" : "Failed";
System.out.println("Exam Result: " + result);
// Modern Switch Expression (Java 14+)
int dayOfWeek = 3;
String dayName = switch (dayOfWeek) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4, 5 -> "Weekend threshold";
default -> "Invalid Day";
};
System.out.println("Day status: " + dayName);
}
}
3 Code Challenge
Challenge: Write a nested conditional checking if a person is old enough to drive (age 16+) and if they possess a valid license (boolean variable). If they have both, print "Safe to drive". Otherwise, specify why they cannot drive. Add a modern switch expression evaluating a character grade ('A', 'B', 'C') to output descriptive reviews (e.g. 'A' -> "Excellent").