Conditionals
Conditionals in Java
Control flow lets your program make decisions based on conditions.
if / else if / else The classic branching construct. Each condition is a boolean expression:
java
if (score >= 90) { grade = "A"; }
else if (score >= 80) { grade = "B"; }
else { grade = "C"; }switch statement
Matches a value against a series of cases. Use break to prevent fall-through:
java
switch (day) {
case "MON": … break;
default: …
}switch expression (Java 14+) The arrow syntax eliminates fall-through and can return a value directly:
java
String label = switch (code) {
case 1 -> "One";
case 2 -> "Two";
default -> "Other";
};Ternary operator A compact inline conditional:
java
String result = (x > 0) ? "positive" : "non-positive";Key points:
- Java switch can match on int, String, enum, and (Java 21+) patterns.
- Always include a
defaultcase in switch statements. - Prefer switch expressions over switch statements for assignments — they are exhaustive.
Code Examples
if/else if/else and ternaryjava
public class Conditionals {
public static void main(String[] args) {
int score = 85;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "F";
}
System.out.println("Grade: " + grade);
boolean passing = score >= 60;
System.out.println(passing ? "Passing" : "Failing");
}
}else-if chains evaluate conditions top-down and execute only the first matching branch.
switch expression (Java 14+)java
public class SwitchExpr {
public static void main(String[] args) {
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
default -> "Weekend";
};
System.out.println("Day: " + dayName);
String season = "SUMMER";
int avgTemp = switch (season) {
case "SUMMER" -> 30;
case "WINTER" -> 2;
case "SPRING", "AUTUMN" -> 15;
default -> 20;
};
System.out.println("Avg temp: " + avgTemp + "°C");
}
}Switch expressions use -> arrows that eliminate fall-through. Multiple labels can share a single arm with commas.
Quick Quiz
1. What happens in a switch statement if you omit `break`?
2. Which syntax can a switch expression return directly?
Was this lesson helpful?