Chapter 6: Control Flow Statements
1. Why Control Flow? (The Big Picture)
Until now, your programs ran top to bottom, line by line — like a straight road. Control flow statements let you:
- Branch (if this condition → do path A, else path B)
- Choose (switch: match this value → execute that block)
- Decide quickly (ternary: one-liner if-else)
Real-life analogy:
- if: “If it’s raining, take umbrella; else, wear sunglasses.”
- switch: “If day is Monday → work; Tuesday → gym; else → relax.”
- Ternary: “Raining? Umbrella : Sunglasses.” (short version)
Java evaluates conditions as boolean (true or false) using relational/logical operators from Chapter 4.
2. The if Statement (Simplest Decision Maker)
Syntax:
|
0 1 2 3 4 5 6 7 8 |
if (condition) { // code runs ONLY if condition is true } |
- Condition must be in ( ) and evaluate to boolean.
- { } are mandatory (even for 1 line — prevents bugs).
- Indent code inside for readability (4 spaces or 1 tab).
Example 1: Basic if (Check if Adult) Complete runnable program:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.Scanner; public class IfDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter your age: "); int age = sc.nextInt(); if (age >= 18) { System.out.println("You are an adult. You can vote!"); } System.out.println("Program continues..."); // Always runs sc.close(); } } |
What happens:
- Input 25 → Prints “You are an adult…” + “Program continues…”
- Input 15 → Only prints “Program continues…” (if block skipped)
Output visualization (for age=25):
|
0 1 2 3 4 5 6 7 8 |
Enter your age: 25 You are an adult. You can vote! Program continues... |
Example 2: if with Complex Condition (Using Logical Operators)
|
0 1 2 3 4 5 6 7 8 9 10 11 |
int marks = 85; int attendance = 90; if (marks >= 60 && attendance >= 75) { System.out.println("Pass! Eligible for exam."); } |
3. if-else (Two Paths: Yes or No)
Syntax:
|
0 1 2 3 4 5 6 7 8 9 10 |
if (condition) { // true path } else { // false path } |
Example: Pass/Fail Checker (Complete program with input)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.Scanner; public class IfElseDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter marks (0-100): "); int marks = sc.nextInt(); if (marks >= 35) { System.out.println("Congratulations! You passed."); System.out.printf("Grade: %.1f%%\n", (marks / 100.0) * 100); } else { System.out.println("Sorry! You failed. Study harder."); System.out.println("Next time target >35 marks."); } sc.close(); } } |
Test cases:
- Marks=45 → “Congratulations! … Grade: 45.0%”
- Marks=20 → “Sorry! … Next time target >35 marks.”
Key Rule: Only one else per if. else runs if all previous ifs fail.
4. if-else if-else Chain (Multiple Conditions)
Syntax:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
if (condition1) { // path 1 } else if (condition2) { // path 2 } else if (condition3) { // path 3 } else { // default (none match) } |
Important:
- Conditions checked top to bottom — first true wins.
- Use else if when conditions are mutually exclusive (only one can be true).
Example: Grading System (Real-world, complete program)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.util.Scanner; public class GradingSystem { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter marks (0-100): "); double marks = sc.nextDouble(); if (marks >= 90) { System.out.println("Grade: A+ (Outstanding!)"); } else if (marks >= 80) { System.out.println("Grade: A (Excellent)"); } else if (marks >= 70) { System.out.println("Grade: B (Good)"); } else if (marks >= 60) { System.out.println("Grade: C (Average)"); } else if (marks >= 35) { System.out.println("Grade: D (Pass - Needs Improvement)"); } else { System.out.println("Grade: F (Fail - Retake the exam)"); } sc.close(); } } |
Test Inputs & Outputs:
| Marks | Output |
|---|---|
| 92 | Grade: A+ (Outstanding!) |
| 75 | Grade: B (Good) |
| 45 | Grade: D (Pass…) |
| 20 | Grade: F (Fail…) |
| -5 | Grade: F (Fail…) |
5. Nested if (if Inside if — Like Russian Dolls)
Syntax: if statements inside other if blocks.
When to use: When you need secondary checks only if primary condition passes.
Example: ATM Pin Checker (Complete runnable program)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.util.Scanner; public class NestedIfDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter ATM Pin: "); int pin = sc.nextInt(); if (pin == 1234) { // Outer if System.out.println("Pin correct! Welcome."); System.out.print("Enter amount to withdraw (max 10000): "); int amount = sc.nextInt(); if (amount > 0 && amount <= 10000) { // Nested if System.out.printf("Dispensing ₹%d. Thank you!\n", amount); } else { System.out.println("Invalid amount! Try 1-10000."); } } else { System.out.println("Wrong Pin! Access denied."); } sc.close(); } } |
Execution Flow:
- Pin=1234, Amount=5000 → “Pin correct! … Dispensing ₹5000.”
- Pin=1234, Amount=15000 → “Pin correct! … Invalid amount!”
- Pin=9999 → “Wrong Pin! Access denied.” (nested if skipped entirely)
Pro Tip: Don’t nest too deep (max 2-3 levels) — use else if chains instead for readability.
6. switch-case Statement (Menu-Like Choices)
Perfect for multiple exact matches (e.g., days, grades, menu options). Java switch works on int, char, String, enum (since Java 7+ Strings allowed).
Syntax (Traditional pre-Java 14):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
switch (expression) { case value1: // code break; case value2: // code break; default: // if no match } |
- break;mandatory — jumps out, else “fall-through” (next cases run too).
- default: optional (like else).
Example 1: Day of Week (Complete program)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import java.util.Scanner; public class SwitchDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter day number (1-7): "); int day = sc.nextInt(); switch (day) { case 1: System.out.println("Monday - Start of work week"); break; case 2: System.out.println("Tuesday - Gym day"); break; case 3: System.out.println("Wednesday - Hump day!"); break; case 4: System.out.println("Thursday - Almost weekend"); break; case 5: System.out.println("Friday - Party time!"); break; case 6: case 7: // Multiple cases same action System.out.println("Weekend - Relax!"); break; default: System.out.println("Invalid day! Enter 1-7."); } sc.close(); } } |
Key Points:
- Day=6 or 7 → “Weekend – Relax!” (fall-through intentional)
- Day=9 → “Invalid day!”
Example 2: switch with String (Java 7+)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
String fruit = "apple"; // Or from Scanner.next() switch (fruit) { case "apple": System.out.println("Red fruit, good for health"); break; case "banana": System.out.println("Yellow, potassium rich"); break; default: System.out.println("Unknown fruit"); } |
Modern Java 14+ switch Expression (Returns a value, arrow syntax — cleaner!)
|
0 1 2 3 4 5 6 7 8 9 10 11 |
String result = switch (day) { case 1 -> "Monday - Work"; case 6, 7 -> "Weekend"; // Multiple with comma default -> "Invalid"; }; System.out.println(result); |
(No break needed! Exhaustive — compiler checks all cases.)
7. Ternary Operator (Quick One-Liner if-else)
Syntax (From Chapter 4, but deep dive here):
|
0 1 2 3 4 5 6 |
variable = (condition) ? valueIfTrue : valueIfFalse; |
- Right-associative — can nest: a ? b : c ? d : e
- Use for simple decisions only (not complex logic).
Example 1: Basic
|
0 1 2 3 4 5 6 7 8 |
int age = 20; String status = (age >= 18) ? "Adult" : "Minor"; System.out.println(status); // Adult |
Example 2: In Printf (Complete program snippet)
|
0 1 2 3 4 5 6 7 8 9 10 |
Scanner sc = new Scanner(System.in); int num = sc.nextInt(); String evenOdd = (num % 2 == 0) ? "Even" : "Odd"; System.out.printf("Number %d is %s\n", num, evenOdd); |
Example 3: Nested Ternary (Use sparingly)
|
0 1 2 3 4 5 6 7 8 9 |
int marks = 85; String grade = (marks >= 90) ? "A+" : (marks >= 80) ? "A" : (marks >= 70) ? "B" : "C"; |
When NOT to use: Complex logic → use if-else for readability.
Summary Tables (Your Quick Cheat Sheets)
if-else Ladder Comparison
| Structure | Best For | Example |
|---|---|---|
| Simple if | Single check | if (balance > 0) |
| if-else | Two options | Pass/Fail |
| else if | Multiple exclusive | Grading A/B/C/D/F |
| Nested if | Dependent checks | Pin correct → amount OK |
| switch | Exact value matches | Menu: 1=Add, 2=Subtract |
| Ternary | Simple assignment | max = (a>b)?a:b; |
switch Fall-Through Behavior
| Without break | With break |
|---|---|
| case 1: case 2: → both run | case 1: … break; → only 1 |
Common Mistakes & Fixes (Learn from Errors!)
| Mistake | Error/Issue | Fix |
|---|---|---|
| if (x = 5) (assignment) | Always true (no comparison) | if (x == 5) or if (x > 5) |
| Forgetting { } | Only 1 line works | Always use { } even for 1 statement |
| No break in switch | Fall-through (wrong cases run) | Add break; after each case |
| if (marks > 100) no else | Invalid marks → nothing happens | Add else { System.out.println(“Invalid”); } |
| Ternary for complex logic | Hard to read | Use if-else instead |
| switch on double/float | Compile error (not allowed) | Use int or String |
| Chained else if forever | Last else never reached | Add default in switch or final else |
Debug Tip: Use System.out.println(“Debug: condition=” + condition); inside if to trace.
Complete Advanced Example: Student Admission System
Puts everything together — nested if, switch, ternary, input/output.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import java.util.Scanner; public class AdmissionSystem { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter 12th marks (0-100): "); double marks12 = sc.nextDouble(); sc.nextLine(); // Clear buffer System.out.print("Stream (Science/Commerce/Arts): "); String stream = sc.nextLine().toLowerCase(); // Nested if + switch + ternary if (marks12 >= 60) { // Primary eligibility String eligibility = switch (stream) { case "science" -> (marks12 >= 90) ? "IIT/NIT" : "Good college"; case "commerce" -> "CA/MBA ready"; case "arts" -> "Top universities"; default -> "Invalid stream"; }; System.out.printf("\n=== Admission Result ===\n"); System.out.printf("Marks: %.1f%%\n", marks12); System.out.printf("Stream: %s\n", stream.toUpperCase()); System.out.printf("Eligible for: %s\n", eligibility); } else { System.out.println("Sorry! Minimum 60%% required. Prepare better."); } sc.close(); } } |
Sample Run (marks12=92, stream=Science):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
Enter 12th marks (0-100): 92 Stream (Science/Commerce/Arts): Science === Admission Result === Marks: 92.0% Stream: SCIENCE Eligible for: IIT/NIT |
Homework (Practice to Master!)
- Basic: Write EvenOddChecker.java — input number, use ternary to print “Even” or “Odd”.
- Medium: BMI Calculator — input weight(kg), height(m). Use if-else chain:
- <18.5: Underweight
- 18.5-24.9: Normal
- 25-29.9: Overweight
-
=30: Obese Use printf “%.1f” for BMI.
- Advanced: Library Menu System — input choice (1-4 via switch):
- 1: Issue book (nested if: member? yes→issue : no→signup)
- 2: Return book
- 3: Check fine (>7 days late → fine)
- 4: Exit Use Scanner for all inputs.
- Debug Challenge: Fix this buggy code:
Java012345678910int x = 10;if (x = 5) // Bug 1System.out.println("Equal"); // Bug 2 (no {})else System.out.println("Not");switch(x){ case 10: case 20: System.out.println("Match"); } // Bug 3
(Expected: “Not”, “Match”)
- Bonus: Compare if-else chain vs switch for grading — time both with System.currentTimeMillis() (hint: switch faster for many cases).
You’ve nailed control flow! This is the brain of your programs — decisions make them useful.
