Conditional branches let a program choose different code paths for different situations. Java uses if, else if, and else for branching.
if
An if statement checks a condition. If the condition is true, Java runs the indented block under it. If the condition is false, Java skips that block.
int age = 17;
if (age > 0 && age < 18) {
System.out.println("Minor");
}One possible run:
Enter your age: 17
MinorIn Java, indentation is not decoration. It is part of the syntax. Statements that belong to the same if block must use the same indentation level.
KNOWLEDGE QUIZ
if-else
if-else is used for a two-way choice: run the if block when the condition is true; otherwise run the else block.
Here is a leap-year example. A year is a leap year if it satisfies one of these conditions:
- It is divisible by 4, and not divisible by 100.
- Or it is divisible by 400.
int year = 2020;
boolean leap = (year % 4 == 0 && year % 100 != 0);
|| year % 400 == 0;
if (leap) {
System.out.println("Leap year");
} else {
System.out.println("Common year");
}One possible run:
Enter a year: 2020
Leap yearSaving the complex condition into is_leap_year makes the if line easier to read. In real programs, this is often more maintainable than placing a long condition directly inside if.
KNOWLEDGE QUIZ
if-else if-else
When there are more than two cases, use if-else if-else. Java checks conditions from top to bottom. It runs the first branch whose condition is true, then skips the remaining branches.
char c = 'T';
if (c >= 'a' && c <= 'z') {
System.out.println("Lowercase");
} else if (c >= 'A' && c <= 'Z') {
System.out.println("Uppercase");
} else if (c >= '0' && c <= '9') {
System.out.println("Digit");
} else {
System.out.println("Special character");
}One possible run:
Enter a character: T
UppercaseThe order of else if branches matters. Put more specific or higher-priority conditions earlier, and use else as the fallback case.
Branch Path Tracer
Select a character and watch Java test conditions from top to bottom, stopping at the first true branch.
KNOWLEDGE QUIZ
Implement a piecewise function
Use different formulas for different ranges of x and print y at the end.
- When x < -2, set y = 0.5 * x + 3.
- When -2 <= x <= 2, set y = 0.
- Otherwise set y = Math.pow(4, x) and print the result.