Branching Logic
Making decisions with if, else, and switch
After this lesson, you will be able to:
- Write
if,if-else, andif-else-ifchains to control program flow - Construct boolean expressions using comparison and logical operators
- Choose between
if-else-ifchains andswitchstatements based on the problem - Avoid common conditional bugs (dangling else, missing braces,
=vs==)
Controlling the Flow
Up to now, your programs have been purely sequential — every line runs, top to bottom. Conditionals let you make decisions: execute this code only if a condition is true.
In Python, you wrote:
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("Below B")
In Java, the structure is similar, but the syntax changes:
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else {
System.out.println("Below B");
}
Key differences: parentheses () around the condition are required. Curly braces {} replace Python’s indentation. elif becomes else if.
Boolean Expressions
Conditions evaluate to true or false. Java provides:
Comparison operators:
| Operator | Meaning |
|---|---|
== |
Equal to |
!= |
Not equal to |
<, > |
Less/greater than |
<=, >= |
Less/greater than or equal |
Logical operators:
| Operator | Meaning | Example |
|---|---|---|
&& |
AND | age >= 18 && age <= 65 |
\|\| |
OR | day == 6 \|\| day == 7 |
! |
NOT | !isDone |
From CSCD 110: Python uses
and,or,not. Java uses&&,||,!. Same logic, different symbols.
1 <= x <= 100. You must use && to combine two separate comparisons. The || version would be true for ANY number. The last option technically works but doesn't match "inclusive" semantics as cleanly.
The if-else-if Chain
For mutually exclusive ranges, use an if-else-if chain. Order matters — Java checks each condition top-to-bottom and takes the first match:
public static char getLetterGrade(int score) {
if (score >= 90) {
return 'A';
} else if (score >= 80) {
return 'B';
} else if (score >= 70) {
return 'C';
} else if (score >= 60) {
return 'D';
} else {
return 'F';
}
}
Because we use else if, we don’t need to write score >= 80 && score < 90. If the code reaches the second branch, we already know score < 90 because the first condition was false.
Switch Statements
When you’re comparing a single variable against exact values (not ranges), switch is cleaner:
switch (dayOfWeek) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6:
case 7: System.out.println("Weekend!"); break;
default: System.out.println("Invalid day");
}
Common Pitfall: Forgetting
breakcauses fall-through — Java continues executing the next case. Cases 6 and 7 above use intentional fall-through (both print “Weekend!”), but accidental fall-through is a frequent bug.
if-else-if for ranges and compound conditions.
Common Mistakes
1. Using = instead of ==:
if (x = 5) { ... } // COMPILER ERROR — assignment, not comparison
if (x == 5) { ... } // Correct — comparison
2. Comparing Strings with ==:
if (name == "Alice") { ... } // WRONG — compares references
if (name.equals("Alice")) { ... } // CORRECT — compares content
3. Omitting braces:
if (x > 0)
System.out.println("positive");
System.out.println("done"); // This ALWAYS runs! Not part of the if.
Always use braces, even for single-line bodies. It prevents bugs and makes code clearer.
Given int x = 15;, what does this code print?if (x > 20) { System.out.println("high"); } else if (x > 10) { System.out.println("mid"); } else { System.out.println("low"); }
Summary
Conditionals control which code runs based on boolean expressions. Use if-else-if for range checks and complex conditions. Use switch for discrete value matching. Always use braces. Compare strings with .equals(), never ==.