Java Choose a Branch
An if statement chooses whether to execute a block. An else branch handles the alternative, and an else-if chain chooses the first condition that matches.
Understand the idea
Put the most specific overlapping rule before a broader one. Once a branch in an if/else-if/else chain is selected, later branches in that chain are skipped. Nested conditions can be appropriate when one decision belongs inside another, but extracting a named boolean can often make the intent clearer. Use braces even for short branches so later edits do not accidentally change the block boundary.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
public class Main {
public static void main(String[] args) {
int available = 2;
int requested = 3;
if (requested <= 0) {
System.out.println("Choose at least one seat");
} else if (requested > available) {
System.out.println("Not enough seats");
} else {
System.out.println("Booking accepted");
}
}
}
Expected output
Not enough seatsThe invalid-size condition is checked first. This request is positive, so execution reaches the capacity condition and prints the refusal. The final branch is reached only after both checks fail. This makes it possible to read the acceptance branch as a case where the request has passed the earlier validation.
Check the official Java documentation for detailed contracts and supported options.