Conditionals
Use if, if-else, else-if, nested conditionals, boolean expressions, De Morgan logic, and short-circuit evaluation.
A lesson of AP Computer Science A, in Control Flow and Methods, about 10 minutes.
Conditionals and Boolean Expressions
By the end of this lesson, you will be able to write complex boolean expressions, use if/else if/else chains, and apply the ternary operator.
Boolean Expressions
int x = 5;
x > 0 && x < 10 // true (both conditions met)
x < 0 || x > 3 // true (second condition met)
!(x == 5) // false (x IS 5, so == is true, NOT makes it false)
Relational operators: ==, !=, <, >, <=, >=
Logical operators:
&&(AND): both must be true||(OR): at least one must be true!(NOT): reverses boolean value
Short-circuit evaluation:
&&: if left side is false, right side is NOT evaluated||: if left side is true, right side is NOT evaluated
This matters when the right side has side effects or could throw an exception.
if / else if / else
if (condition1) {
// runs if condition1 is true
} else if (condition2) {
// runs if condition1 false AND condition2 true
} else if (condition3) {
// runs if conditions 1,2 false AND condition3 true
} else {
// runs if ALL conditions above are false
}
Once a condition is true, the rest are SKIPPED.
int score = 85;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) { // only checked if score < 90
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "F";
}
// grade = "B"
Common Mistake: Overlapping Conditions
// WRONG order:
if (score >= 70) { grade = "C"; } // this catches everything ≥ 70 first!
else if (score >= 80) { grade = "B"; } // never reached for scores 80-89
else if (score >= 90) { grade = "A"; } // never reached for scores ≥ 90
If conditions aren't mutually exclusive, order matters:
Always arrange conditions from most restrictive to least, or least to most (consistently).
Nested Conditionals
if (isLoggedIn) {
if (isAdmin) {
System.out.println("Admin panel");
} else {
System.out.println("User dashboard");
}
} else {
System.out.println("Please log in");
}
Deeply nested conditionals are hard to read — consider refactoring with methods.