Chapter 7: Conditionals
Introduction
Learning Outcomes
Distinguish sequential, selection and repetition flow.
Write conditions with comparison and logical operators.
Write if, else if and else in the right order.
Use switch for discrete choices.
Basics
Three Basic Control Structures
- Sequence runs statements in the order written; selection picks a path based on a condition.
- A loop repeats a block of code.
- Every algorithm is built from these three structures.
Basics
Sequential Statements
double base = 8; double height = 5; double area = base * height / 2; System.out.println(area);
- Each statement can use values produced by earlier ones.
- Change the order and you may get an undefined or wrong value.
Basics · Step through the code
Sequential Statements Step by Step
base = 8 → stored in a double box as 8.0 (widening).
height = 5.0.
Left to right: first base * height = 40.0.
40.0 / 2 = 20.0 → stored in area. This line uses the values of the two boxes above.
20.0 is printed. Had line 3 come before line 1, base would not exist yet → compile error.
double base = 8; double height = 5; double area = base * height / 2; System.out.println(area);
Decisions
Making Decisions
- A condition produces a boolean value.
- if defines the true path, else the false path.
- Every independent if is tested; in an else-if chain, once the first true branch runs the rest are skipped.
- Example: score = 95. On the right, two versions with different results.
Decisions
The if-else Statement
if (score >= 60) { System.out.println("Pass"); } else { System.out.println("Fail"); }
- The boundary belongs to the condition: 60 → Pass.
- Every possible value goes to exactly one branch.
Decisions · Step through the code
if-else Step by Step: score = 75, 60, 45
Run 1: the user enters 75.
Condition: score >= 60 → 75 >= 60 → true.
The true branch runs: Pass. The else block is skipped.
Run 2: the user enters 60.
Condition: score >= 60 → 60 >= 60 → true. The boundary is included: >=.
The true branch runs: Pass. The else block is skipped.
Run 3: the user enters 45.
Condition: score >= 60 → 45 >= 60 → false.
The false branch runs: Fail. The if block is skipped.
Scanner in = new Scanner(System.in); int score = in.nextInt(); if (score >= 60) { System.out.println("Pass"); } else { System.out.println("Fail"); }
Decisions
Multiway Decisions: else-if
if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else { grade = 'F'; }
- Conditions are tested top to bottom; the first true branch runs and the rest are skipped.
- Put the higher thresholds first: with
score >= 70on top, 95 would also get a C. - else runs when no condition holds.
Decisions · Step through the code
else-if Chain: score = 75, 95, 50
Run 1: score = 75. grade is declared but has no value yet.
Condition 1: score >= 90 → 75 >= 90 → false. Move on to the next one.
Condition 2: score >= 80 → 75 >= 80 → false. Move on to the next one.
Condition 3: score >= 70 → 75 >= 70 → true. This branch is taken.
grade = 'C'. The rest of the chain is skipped without testing.
C is printed.
Run 2: score = 95. grade is declared but has no value yet.
Condition 1: score >= 90 → 95 >= 90 → true. This branch is taken.
grade = 'A'. The rest of the chain is skipped without testing.
A is printed.
Run 3: score = 50. grade is declared but has no value yet.
Condition 1: score >= 90 → 50 >= 90 → false. Move on to the next one.
Condition 2: score >= 80 → 50 >= 80 → false. Move on to the next one.
Condition 3: score >= 70 → 50 >= 70 → false. Move on to the next one.
No condition held → else: grade = 'F'.
F is printed.
int score = in.nextInt(); char grade; if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else grade = 'F'; System.out.println(grade);
Braces may be omitted when a branch has a single statement.
Decisions · Step through the code
Independent if Statements: score = 95 → 3 lines
score = 95. The three ifs are independent; none is the else branch of another.
95 >= 90 → true → A is printed. Because the ifs are independent, the next one is tested anyway.
95 >= 80 → true → B is printed too. The previous if has no effect on this test.
95 >= 70 → true → C is printed too. Result: 3 lines instead of one grade, which is wrong.
int score = 95; if (score >= 90) System.out.println("A"); if (score >= 80) System.out.println("B"); if (score >= 70) System.out.println("C");
Decisions · Step through the code
Same score = 95, else-if chain → 1 line
Same score = 95; this time the conditions are chained with else if.
95 >= 90 → true → A is printed.
The first branch ran, so the else if branches are never evaluated; 80 and 70 are not tested.
Result: just 1 line. Independent ifs print 3 lines (A, B, C); the else-if chain prints 1 (A).
int score = 95; if (score >= 90) System.out.println("A"); else if (score >= 80) System.out.println("B"); else if (score >= 70) System.out.println("C");
Decisions
Nested Decisions
- A branch can contain another decision: the inner condition is tested only when the outer one is true.
- Nesting fits cases where the second question only makes sense once the first condition holds.
- Deep nesting hurts readability; conditions can be combined with
&&.
Decisions · Step through the code
Nested Decision: 3 different inputs
Run 1: age = 20, license = true.
Outer condition: age >= 18 → 20 >= 18 → true. Enter the inner if.
Inner condition: license → true.
Can drive is printed.
Run 2: age = 20, license = false.
Outer condition: age >= 18 → 20 >= 18 → true. Enter the inner if.
Inner condition: license → false.
Get a license first is printed.
Run 3: age = 15, license = true.
Outer condition: 15 >= 18 → false. The inner if is never tested; license does not matter.
The outer else runs: Too young.
int age = in.nextInt(); boolean license = in.nextBoolean(); if (age >= 18) { if (license) System.out.println("Can drive"); else System.out.println("Get a license first"); } else { System.out.println("Too young"); }
Decisions · Step through the code
The Dangling else: a = −1
Start: a = -1, b = 5, x = 0. The indentation suggests the else belongs to the outer if, but the compiler ignores indentation.
a > 0 → −1 > 0 → false. The whole body of the outer if (inner if and its else included) is skipped.
else binds to the nearest if (if (b > 0)); that if never ran, so neither did the else. x is unchanged: 0 is printed.
int a = -1, b = 5, x = 0; if (a > 0) if (b > 0) x = 1; else x = 2; System.out.println(x);
Decisions · Step through the code
Fixing the Dangling else with Braces
Same starting values. This time the inner if is wrapped in braces; the else belongs to the outer if.
a > 0 → false. The inner if block is skipped and control goes to the else block.
The else block runs: x = 2.
2 is printed. Always use braces with nested ifs to remove the ambiguity.
int a = -1, b = 5, x = 0; if (a > 0) { if (b > 0) x = 1; } else { x = 2; } System.out.println(x);
Decisions
Decisions with Logical Operators
boolean eligible = age >= 18 && hasDoc; if (eligible) { System.out.println("Application accepted"); }
- && requires both conditions to be true.
- || requires at least one of them to be true.
Decisions · Step through the code
Deciding with &&: 3 different inputs
Run 1: age = 20, hasDoc = true.
20 >= 18 → true; the right side is needed: hasDoc → true. true && true → true.
Application accepted is printed.
Run 2: age = 20, hasDoc = false.
20 >= 18 → true; the right side is needed: hasDoc → false. true && false → false.
eligible is false → the block is skipped, no output.
Run 3: age = 16, hasDoc = true.
16 >= 18 → false. Short circuit: hasDoc is not read; the result is already false.
eligible is false → the block is skipped, no output.
int age = in.nextInt(); boolean hasDoc = in.nextBoolean(); boolean eligible = age >= 18 && hasDoc; if (eligible) { System.out.println("Application accepted"); }
Decisions
! and De Morgan's Laws
| a | b | !(a && b) | !a || !b | !(a || b) | !a && !b |
|---|---|---|---|---|---|
| false | false | true | true | true | true |
| false | true | true | true | false | false |
| true | false | true | true | false | false |
| true | true | false | false | false | false |
// Reject: under 18 or no document if (!(age >= 18 && hasDoc)) { … } // Same condition by De Morgan: if (age < 18 || !hasDoc) { … }
- Pushing
!inside the parentheses swaps&&and||and negates each term. - Negated comparisons:
>=↔<,>↔<=,==↔!=.
Decisions
Non-Short-Circuit & and |
int a = 10, b = 0; if (b != 0 && a / b > 1) { … } // safe: a / b never runs if (b != 0 & a / b > 1) { … } // ArithmeticException: / by zero
The single-character & and | also work on booleans, but they always evaluate both sides.
static int count = 0; static boolean check(boolean v) { count++; return v; }
| Expression (count starts at 0) | count |
|---|---|
check(false) && check(true) | 1 |
check(false) & check(true) | 2 |
check(true) || check(true) | 1 |
check(true) | check(true) | 2 |
Decisions · Step through the code
The Conditional Operator: (a > b) ? a : b
a = 7, b = 12.
Condition: a > b → 7 > 12 → false, so the value after : is chosen.
max = 12. ?: is an expression: it yields a value that can be assigned.
12 is printed. The same if-else takes 4 lines.
int a = 7, b = 12; int max = (a > b) ? a : b; System.out.println(max);
Use it for short two-way value choices; nested ?: hurts readability.
Decisions · Step through the code
Comparing Strings: == vs. equals
The literal "java" is created in the string pool; s1 holds a reference to it.
Writing the same literal again shares the pooled object; s2 points to the same object.
new String("java") always creates a new object; s3 points to a separate object on the heap.
== compares references (addresses). s1 and s2 point to the same object, so true.
s1 and s3 have the same contents but are different objects → different addresses → false.
equals compares the contents: "java" = "java" → true. Always compare strings with equals.
String s1 = "java"; String s2 = "java"; String s3 = new String("java"); System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s1.equals(s3));
switch
When to Use switch
- It suits a choice among the discrete values of a single expression.
- case labels name the fixed options; control jumps directly to the matching case.
- For ranges and complex logical conditions, if-else is usually a better fit.
switch
The switch Expression
String season = switch (month) { case 12, 1, 2 -> "Winter"; case 3, 4, 5 -> "Spring"; case 6, 7, 8 -> "Summer"; case 9, 10, 11 -> "Autumn"; default -> "Invalid"; };
- The arrow form prevents accidental fall-through into the next case.
- default handles unexpected values. A switch expression (
x = switch …) must cover every value, so for int and Stringdefaultis required; in a switch statement it is optional. This syntax needs Java 14 or later.
switch · Step through the code
switch Expression: month = 4, 12, 13
Run 1: month = 4.
switch (month) → 4: 4 is in this case's list. The selected branch yields "Spring".
The value of the switch expression is assigned: season = "Spring". No other case runs.
Spring is printed.
Run 2: month = 12.
switch (month) → 12: 12 is in this case's list. The selected branch yields "Winter".
The value of the switch expression is assigned: season = "Winter". No other case runs.
Winter is printed.
Run 3: month = 13.
switch (month) → 13: no case lists 13 → default. The selected branch yields "Invalid".
The value of the switch expression is assigned: season = "Invalid". No other case runs.
Invalid is printed.
int month = in.nextInt(); String season = switch (month) { case 12, 1, 2 -> "Winter"; case 3, 4, 5 -> "Spring"; case 6, 7, 8 -> "Summer"; case 9, 10, 11 -> "Autumn"; default -> "Invalid"; }; System.out.println(season);
switch
yield in a switch Expression
int year = 2024, month = 2; int days = switch (month) { case 4, 6, 9, 11 -> 30; case 2 -> { System.out.println("February"); yield year % 4 == 0 ? 29 : 28; } default -> 31; }; System.out.println(days);
Output: February and 29 (two lines).
- A single-expression branch gives its value directly; when several statements are needed, wrap the branch in a
{ }block and give the value withyield. - A block that ends without
yieldis a compile error:switch rule completes without providing a value. - Requires Java 14 or later; the leap-year test is simplified here (no 100/400 rule).
switch · Step through the code
Classic switch: Forgetting break
day = 2.
switch (day) → 2: control jumps straight to case 2; case 1 is never tested.
"Tue" is printed. This case has no break!
Fall-through: the next case's code runs too, without testing its label → "Wed".
break leaves the switch; default does not run. The arrow (->) form avoids this bug.
int day = 2; switch (day) { case 1: System.out.println("Mon"); break; case 2: System.out.println("Tue"); case 3: System.out.println("Wed"); break; default: System.out.println("None"); }
switch
if-else vs. switch
| Criterion | if-else | switch |
|---|---|---|
| Range condition | Good fit | Not directly |
| Many choices on one value | Works | Usually clearer |
| Complex logic | Good fit | Limited |
| Each branch yields a value | Needs an assignment | A switch expression can return a value |
Example
Odd or Even?
int num = 17; if (num % 2 == 0) System.out.println("Even"); else System.out.println("Odd");
- A number is even if dividing by 2 leaves a remainder of 0.
- This works for negatives too. But in Java -7 % 2 = -1, so testing odd numbers with
num % 2 == 1is wrong.
Example · Step through the code
Odd or Even? num = 17, −4, −7
Run 1: num = 17.
First the remainder: 17 % 2 = 1.
1 == 0 → false.
Odd is printed.
Run 2: num = -4.
First the remainder: -4 % 2 = 0.
0 == 0 → true.
Even is printed.
Run 3: num = -7.
First the remainder: -7 % 2 = -1 (in Java the remainder takes the sign of the dividend).
-1 == 0 → false.
Odd is printed. With the test -7 % 2 == 1 the result would have been false!
int num = in.nextInt(); if (num % 2 == 0) System.out.println("Even"); else System.out.println("Odd");
Example
Absolute Value
int num = -8; if (num < 0) { num = -num; } System.out.println(num);
- Zero and positive values stay unchanged.
- Integer.MIN_VALUE is a special overflow case.
Example · Step through the code
Absolute Value: num = −8, 5, MIN_VALUE
Run 1: num = -8.
Condition: num < 0 → -8 < 0 → true.
num = -num → -(-8) = 8.
8 is printed.
Run 2: num = 5.
Condition: num < 0 → 5 < 0 → false. The block is skipped; the value stays.
5 is printed.
Run 3: num = -2147483648 (Integer.MIN_VALUE).
Condition: num < 0 → -2147483648 < 0 → true.
-(-2147483648) = 2147483648 does not fit in an int → overflow: the result is -2147483648 again!
-2147483648 is printed. The absolute value came out negative: a special case.
int num = in.nextInt(); if (num < 0) { num = -num; } System.out.println(num);
Example · Step through the code
Leap Year: 2024, 2023, 1900, 2000
Run 1: year = 2024.
2024 % 4 = 0 → true; 2024 % 100 = 24 → year % 100 != 0 → true. Parenthesized part: true.
Left side true → || short-circuits: the 400 rule is not checked. leap = true.
2024 is a leap year.
Run 2: year = 2023.
2023 % 4 = 3 → false; && short-circuits. Parenthesized part: false.
Left side false → check the right: 2023 % 400 = 23 → false. leap = false.
2023 is not a leap year.
Run 3: year = 1900.
1900 % 4 = 0 → true; 1900 % 100 = 0 → year % 100 != 0 → false. Parenthesized part: false.
Left side false → check the right: 1900 % 400 = 300 → false. leap = false.
1900 is not a leap year. Century years are leap years only if divisible by 400.
Run 4: year = 2000.
2000 % 4 = 0 → true; 2000 % 100 = 0 → year % 100 != 0 → false. Parenthesized part: false.
Left side false → check the right: 2000 % 400 = 0 → true. leap = true.
2000 is a leap year.
int year = in.nextInt(); boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; if (leap) System.out.println(year + " is a leap year"); else System.out.println(year + " is not a leap year");
Example · Step through the code
Quadratic Equation: Δ > 0, Δ = 0, Δ < 0
Run 1: a = 1.0, b = -3.0, c = 2.0.
d = Δ = b² − 4ac = 9.0 − 8.0 = 1.0.
1.0 > 0 → true: two distinct real roots.
√Δ = 1.0; x1 = (3.0 + 1.0) / 2.0 = 2.0, x2 = 1.0.
2.0 and 1.0: the parabola crosses the x-axis at two points.
Run 2: a = 1.0, b = -2.0, c = 1.0.
d = Δ = b² − 4ac = 4.0 − 4.0 = 0.0.
Δ > 0 is false; Δ == 0 → true: one (double) root.
x = −b / 2a = 2.0 / 2.0 = 1.0: the parabola touches the axis.
Run 3: a = 1.0, b = 0.0, c = 1.0.
d = Δ = b² − 4ac = 0.0 − 4.0 = -4.0.
-4.0 > 0 false, -4.0 == 0 false → else.
No real roots: the parabola never meets the axis. Math.sqrt of a negative would give NaN; the else prevents that.
double a = in.nextDouble(); double b = in.nextDouble(); double c = in.nextDouble(); double d = b * b - 4 * a * c; if (d > 0) { double x1 = (-b + Math.sqrt(d)) / (2 * a); double x2 = (-b - Math.sqrt(d)) / (2 * a); System.out.println(x1 + " and " + x2); } else if (d == 0) { System.out.println(-b / (2 * a)); } else { System.out.println("No real roots"); }
Example · Step through the code
Largest of Three Numbers: 3 different inputs
Run 1: 7, 12, 5.
Candidate: max = a = 7.
b > max → 12 > 7 → true.
New candidate: max = b = 12.
c > max → 5 > 12 → false; the candidate stays.
Max: 12.
Run 2: 3, 3, 9.
Candidate: max = a = 3.
b > max → 3 > 3 → false; the candidate stays. An equal value does not replace it.
c > max → 9 > 3 → true.
New candidate: max = c = 9.
Max: 9.
Run 3: 8, 2, 4.
Candidate: max = a = 8.
b > max → 2 > 8 → false; the candidate stays.
c > max → 4 > 8 → false; the candidate stays.
Max: 8.
int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); int max = a; if (b > max) max = b; if (c > max) max = c; System.out.println("Max: " + max);
Shortcut: Math.max(a, Math.max(b, c)). The "candidate + compare" pattern generalizes with a loop.
Example · Step through the code
A Calculator with switch: *, /0, %
Run 1: the user enters 8.0 * 2.5; next() reads the operator as a string.
switch (op) → "*": matches case "*".
8.0 * 2.5 = 20.0 is printed. No other case runs.
Run 2: the user enters 7.0 / 0.0; next() reads the operator as a string.
switch (op) → "/": matches case "/".
Check before dividing: y == 0 → true. (With doubles 7.0 / 0 does not throw; it gives Infinity, so we check.)
Error! is printed.
Run 3: the user enters 5.0 % 3.0; next() reads the operator as a string.
switch (op) → "%": no case matches → default.
Invalid: this calculator has no %; default catches unexpected input.
double x = in.nextDouble(); String op = in.next(); double y = in.nextDouble(); switch (op) { case "+" -> System.out.println(x + y); case "-" -> System.out.println(x - y); case "*" -> System.out.println(x * y); case "/" -> { if (y == 0) System.out.println("Error!"); else System.out.println(x / y); } default -> System.out.println("Invalid"); }
Summary
Chapter Summary
- Sequence runs statements in the order written; selection picks a path based on a condition.
- A condition must always produce a boolean value.
- In an else-if chain, conditions are tried top to bottom; the first true branch runs.
- Use if-else for ranges and complex conditions, switch for discrete values of one expression.
Summary
Review Questions
- How do independent if statements differ from an else-if chain?
- Why are the thresholds written from highest to lowest when converting scores to letter grades?
- When can && replace a nested decision?
- Why is default useful in a switch?
- Which condition tells you that a number is even?
Summary
Exercises
- Print whether an input integer is positive, negative or zero.
- Compute body mass index (weight / height²) and print underweight / normal / overweight.
- Do three side lengths form a triangle? If so, is it equilateral, isosceles or scalene?
- Map a day number 1–7 to a day name with switch; warn on invalid input.
- Find the smaller of two numbers with
?:, then extend it to three numbers. - Add an "outside 0–100" check to the letter-grade program. Where in the chain should it go?
Summary
References
- Deitel and Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2018.
- Liang, Introduction to Java Programming and Data Structures, 13th ed., Pearson, 2024.
- Oracle, The Java Tutorials: The if-then and if-then-else Statements, The switch Statement.
- Oracle, Java Language Specification SE 21: Chapter 14, Blocks, Statements, and Patterns.
- Sedgewick and Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 1.3 Conditionals and Loops.
- Downey and Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (free online edition).