Avoiding Conditional
Bugs in Java
Master the subtle traps in if/else logic, from operator ordering to boundary conditions, and write conditionals that work correctly every time.
What Is a Conditional Bug?
A conditional bug occurs when an if, else if, or else statement does not behave the way the programmer intended. The code compiles and runs, but it produces the wrong result for certain inputs.
Why Conditionals Go Wrong
How Java Evaluates Conditionals
The Golden Rules of Conditionals
\( == \) vs \( = \) : The Classic Trap
Boundary Detail: \( < \) vs \( \leq \)
A grading program awards a B for scores from 80 to 89 (integer). Both conditions below are equivalent for integers:
The Shadowing Bug
When a broader condition is placed before a narrower one, the narrow branch can never execute.
Visualizing Boundary Conditions
Bug-Proofing Checklist
Example 1: Ticket Pricing
A theater charges: Child (age \( < \) 13): $8, Teen (age 13-17): $12, Adult (age \( \geq \) 18): $15. Find the bug:
Example 1: Fixed Ticket Pricing
Example 2: Temperature Warnings
A weather app classifies temperature: Freezing (\( \leq 32 \)), Cold (33-50), Mild (51-75), Hot (\( > 75 \)). Find two bugs:
Example 2: Fixed Temperature
Common Mistakes to Avoid
Bug Type Summary
| Bug Type | Symptom | Fix |
|---|---|---|
| Shadowed branch | A branch never executes | Narrow conditions first |
| Off-by-one | Boundary value goes to wrong branch | Use \( < \) vs \( \leq \) deliberately |
| \( = \) vs \( == \) | Assignment instead of comparison | Always use \( == \) for equality |
| Missing else | Multiple branches fire | Chain with else if |
| String \( == \) | Reference comparison fails | Use .equals() method |
Question 1 of 5
What is the output when score = 95?
if (score >= 60) {
System.out.println("Pass");
} else if (score >= 90) {
System.out.println("Honor Roll");
} else {
System.out.println("Fail");
}
Question 2 of 5
Which operator should replace the ? so that exactly the values 1 through 10 print "In range"?
if (x >= 1 && x ? 10) {
System.out.println("In range");
}
Question 3 of 5
What happens when this code runs with found initially set to false?
boolean found = false;
if (found = true) {
System.out.println("Found it!");
}
if (found)).Question 4 of 5
A program categorizes ages: Child (0-12), Teen (13-17), Adult (18+). Which code is correct?
Question 5 of 5
What is the best first step when debugging a conditional that produces wrong output for some inputs?