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:

Java
  • 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:

Java

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):

text

Example 2: if with Complex Condition (Using Logical Operators)

Java

3. if-else (Two Paths: Yes or No)

Syntax:

Java

Example: Pass/Fail Checker (Complete program with input)

Java

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:

Java

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)

Java

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)

Java

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):

Java
  • break;mandatory — jumps out, else “fall-through” (next cases run too).
  • default: optional (like else).

Example 1: Day of Week (Complete program)

Java

Key Points:

  • Day=6 or 7 → “Weekend – Relax!” (fall-through intentional)
  • Day=9 → “Invalid day!”

Example 2: switch with String (Java 7+)

Java

Modern Java 14+ switch Expression (Returns a value, arrow syntax — cleaner!)

Java

(No break needed! Exhaustive — compiler checks all cases.)

7. Ternary Operator (Quick One-Liner if-else)

Syntax (From Chapter 4, but deep dive here):

Java
  • Right-associative — can nest: a ? b : c ? d : e
  • Use for simple decisions only (not complex logic).

Example 1: Basic

Java

Example 2: In Printf (Complete program snippet)

Java

Example 3: Nested Ternary (Use sparingly)

Java

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.

Java

Sample Run (marks12=92, stream=Science):

text

Homework (Practice to Master!)

  1. Basic: Write EvenOddChecker.java — input number, use ternary to print “Even” or “Odd”.
  2. 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.

  3. 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.
  4. Debug Challenge: Fix this buggy code:
    Java

    (Expected: “Not”, “Match”)

  5. 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.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *