control flow
Making Decisions in Code
Control flow statements let your program choose different paths depending on conditions. Java offers if, if-else, else if, and switch for this.
The if Statement
int age = 20;
if (age >= 18) {
System.out.println("You are an adult.");
}The code inside the curly braces {} only runs if the condition evaluates to true.
The if-else Statement
int age = 15;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}Chaining with else if
int score = 75;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 75) {
System.out.println("Grade: B");
} else if (score >= 60) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}Java checks each condition top to bottom and stops at the first one that is true. In this example, since score is 75, it prints "Grade: B" and skips the rest.
Nested Conditionals
You can place an if statement inside another one to check multiple layers of conditions:
int age = 20;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("You can drive.");
} else {
System.out.println("You need a license first.");
}
} else {
System.out.println("You are too young to drive.");
}The Ternary Operator
For simple if-else logic that just assigns a value, the ternary operator is a compact alternative:
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";The format is: condition ? valueIfTrue : valueIfFalse.
The switch Statement
When you're comparing one variable against many possible fixed values, switch is often cleaner than a long else if chain.
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Unknown";
}
System.out.println(dayName); // Wednesday
Important: Don't forget thebreakstatement after each case. Without it, execution "falls through" into the next case, running its code too — even if the condition doesn't match.
Modern Switch Expressions (Java 14+)
Newer versions of Java support a more concise arrow syntax that doesn't need break:
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Unknown";
};Quick Comparison
| Use Case | Best Choice |
|---|---|
| Range checks (e.g. score >= 90) | if / else if |
| Comparing one variable to many exact values | switch |
| Simple value assignment based on a condition | Ternary operator ? : |
Coming up next: We'll explore loops — how to repeat actions usingfor,while, anddo-while.