Wiki Nzar Dev Logo

Control Flow: If, Switch, Loops

The Foundation

What Is Control Flow? -> Control flow is the order in which your code executes.

By default, Java executes code line-by-line, top to bottom:

int age = 25;
System.out.println("Line 1");
System.out.println("Line 2");
System.out.println("Line 3");

// Output:
// Line 1
// Line 2
// Line 3

But what if you want to skip lines? Run lines multiple times? Make decisions based on conditions?

That's control flow.

Control flow statements change the execution path:

  • Conditionals (if, switch) -> Skip or execute code based on conditions
  • Loops (for, while) -> Repeat code multiple times

Without control flow, you're just listing instructions. With it, you're building intelligence.


Conditionals (if / switch)

Conditionals execute code only if a condition is true.

The if Statement

The simplest conditional:

if (condition) {
    // Execute this block if condition is true
}

Example:

int age = 25;

if (age >= 18) {
    System.out.println("You can vote");  // This runs
}

System.out.println("Done");  // This always runs

How it works:

Check: is age >= 18?
  Yes → Run the block
  No → Skip the block
Continue with rest of code

The if-else Statement

Execute one block if true, a different block if false:

if (condition) {
    // Execute if true
} else {
    // Execute if false
}

Example:

int age = 15;

if (age >= 18) {
    System.out.println("You can vote");
} else {
    System.out.println("You cannot vote");  // This runs
}

Only one block executes. Never both.

The if-else if-else Chain

Check multiple conditions:

if (condition1) {
    // Execute if condition1 is true
} else if (condition2) {
    // Execute if condition1 is false AND condition2 is true
} else if (condition3) {
    // Execute if condition1 and condition2 are false AND condition3 is true
} else {
    // Execute if all conditions are false
}

Example:

int score = 85;

if (score >= 90) {
    System.out.println("Grade: A");
} else if (score >= 80) {
    System.out.println("Grade: B");  // This runs
} else if (score >= 70) {
    System.out.println("Grade: C");
} else {
    System.out.println("Grade: F");
}

Important: Once a condition is true, Java exits the chain. It doesn't check remaining conditions.

Check score >= 90? No
Check score >= 80? Yes → Execute "Grade: B" → EXIT
Don't check score >= 70 (already found answer)

Nested if Statements

if statements inside if statements:

int age = 25;
boolean hasLicense = true;

if (age >= 18) {  // First decision
    if (hasLicense) {  // Second decision (nested)
        System.out.println("You can drive");  // This runs
    } else {
        System.out.println("You need a license");
    }
} else {
    System.out.println("Too young");
}

Nested if statements are useful, but they can get hard to read. Use logical operators instead when possible:

// Better: Use && instead of nesting
if (age >= 18 && hasLicense) {
    System.out.println("You can drive");
}

The switch Statement: Multiple Conditions

When you have many conditions checking the same variable, switch is cleaner than if-else if-else:

switch (value) {
    case value1:
        // Execute if value equals value1
        break;
    case value2:
        // Execute if value equals value2
        break;
    case value3:
        // Execute if value equals value3
        break;
    default:
        // Execute if no cases match
}

Example:

int dayOfWeek = 3;
String dayName;

switch (dayOfWeek) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";  // Matches, executes here
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    default:
        dayName = "Invalid day";
}

System.out.println(dayName);  // "Wednesday"

Critical: The break Statement

Always use break at the end of each case!

Without break, Java continues executing the next case (called "fall-through"):

int day = 1;

switch (day) {
    case 1:
        System.out.println("Monday");  // Prints this
        // MISSING break!
    case 2:
        System.out.println("Tuesday");  // Also prints this (wrong!)
    case 3:
        System.out.println("Wednesday");  // Also prints this (wrong!)
        break;
}

// Output:
// Monday
// Tuesday
// Wednesday

This is usually a bug. Use break to stop after each case:

switch (day) {
    case 1:
        System.out.println("Monday");
        break;  // Stop here
    case 2:
        System.out.println("Tuesday");
        break;  // Stop here
    case 3:
        System.out.println("Wednesday");
        break;  // Stop here
}

// Output: Monday

When Fall-Through Is Intentional

Sometimes you want multiple cases to execute the same code:

int month = 2;
int days;

switch (month) {
    case 1: case 3: case 5: case 7: case 8: case 10: case 12:
        days = 31;  // These months have 31 days
        break;
    case 4: case 6: case 9: case 11:
        days = 30;  // These months have 30 days
        break;
    case 2:
        days = 28;  // February (ignoring leap years for simplicity)
        break;
    default:
        days = 0;
}

System.out.println("Days: " + days);  // 28

switch vs if-else if-else

SituationUse
Checking one variable against multiple valuesswitch
Complex conditions (>, <, ranges)if-else if-else
Logical combinations (&&, ||)if-else if-else
Single equality checksswitch

Loops (while / for)

Loops execute a block of code multiple times.

The while Loop

Repeat while a condition is true:

while (condition) {
    // Execute this block while condition is true
}

Example:

int count = 0;

while (count < 5) {
    System.out.println("Count: " + count);
    count++;  // Increment (otherwise infinite loop!)
}

Output:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

How it works:

Iteration 1: count = 0, check 0 < 5? Yes → print "Count: 0" → count = 1
Iteration 2: count = 1, check 1 < 5? Yes → print "Count: 1" → count = 2
Iteration 3: count = 2, check 2 < 5? Yes → print "Count: 2" → count = 3
Iteration 4: count = 3, check 3 < 5? Yes → print "Count: 3" → count = 4
Iteration 5: count = 4, check 4 < 5? Yes → print "Count: 4" → count = 5
Next check: count = 5, check 5 < 5? No → Exit loop

The do-while Loop

Execute at least once, then repeat while condition is true:

do {
    // Execute this block at least once
} while (condition);

Example:

int count = 0;

do {
    System.out.println("Count: " + count);
    count++;
} while (count < 5);

Same output as while, but the block runs at least once even if the condition starts false:

int count = 10;

do {
    System.out.println("This runs once");  // Runs even though 10 < 5 is false
} while (count < 5);

System.out.println("Done");

Output:

This runs once
Done

The for Loop

Repeat a specific number of times:

for (initialization; condition; increment) {
    // Execute this block
}

Example:

for (int i = 0; i < 5; i++) {
    System.out.println("i: " + i);
}

Output:

i: 0
i: 1
i: 2
i: 3
i: 4

How it works:

1. Initialization: int i = 0 (happens once, before loop starts)
2. Check condition: 0 < 5? Yes → execute block
3. Increment: i++ (i becomes 1)
4. Check condition: 1 < 5? Yes → execute block
5. Increment: i++ (i becomes 2)
... continue until condition is false

for vs while

Use CaseLoop Type
Repeat specific number of timesfor
Repeat until condition changeswhile
Must run at least oncedo-while

for is cleaner when you know the count:

// For: Clear how many iterations
for (int i = 0; i < 10; i++) {
    // Run 10 times
}

// While: Must read carefully to understand
int i = 0;
while (i < 10) {
    // ...
    i++;
}

The for-each Loop

Loop through every element in a collection:

for (type variable : collection) {
    // Execute for each element
}

Example:

String[] names = {"Nzar", "Bob", "Charlie"};

for (String name : names) {
    System.out.println("Name: " + name);
}

Output:

Name: Nzar
Name: Bob
Name: Charlie

How it works:

Iteration 1: name = names[0] = "Nzar" → print
Iteration 2: name = names[1] = "Bob" → print
Iteration 3: name = names[2] = "Charlie" → print
No more elements → Exit loop

for-each vs traditional for:

// Traditional for loop
for (int i = 0; i < names.length; i++) {
    System.out.println(names[i]);
}

// for-each loop (cleaner)
for (String name : names) {
    System.out.println(name);
}

for-each is cleaner when you just need elements. Use traditional for when you need the index.

Loop with Collections

for-each works with any collection:

ArrayList<Integer> scores = new ArrayList();
scores.add(95);
scores.add(87);
scores.add(92);

for (int score : scores) {
    System.out.println("Score: " + score);
}

Output:

Score: 95
Score: 87
Score: 92

break and continue

Explains loop control by showing how break stops loops and continue skips to the next iteration.

The break Statement

Exit a loop immediately:

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;  // Exit loop when i equals 5
    }
    System.out.println(i);
}

Output:

0
1
2
3
4

The loop exits when i reaches 5. Remaining iterations don't run.

Real example: Search for an item

String[] names = {"Nzar", "Bob", "Charlie", "Diana"};
String target = "Charlie";
int index = -1;

for (int i = 0; i < names.length; i++) {
    if (names[i].equals(target)) {
        index = i;
        break;  // Found it, exit loop
    }
}

System.out.println("Found at index: " + index);  // 2

The continue Statement

Skip/Ignore the current iteration, move to the next:

for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue;  // Ignore even numbers
    }
    System.out.println(i);
}

Output:

1
3
5
7
9

Even numbers are skipped. The loop continues, but that iteration's body is jumped over.

Comparison:

// break: Exit entirely
for (int i = 0; i < 10; i++) {
    if (i == 5) break;
    System.out.println(i);  // Prints 0-4, then exits
}

// continue: Skip this iteration, continue loop
for (int i = 0; i < 10; i++) {
    if (i == 5) continue;
    System.out.println(i);  // Prints 0-4, 6-9 (skips 5)
}

Real-World Examples

Example 1: Grade Checker

public class GradeChecker {
    public static void main(String[] args) {
        int[] scores = {95, 67, 88, 72, 91, 45, 85};

        System.out.println("Passing scores (>= 70):");
        for (int score : scores) {
            if (score >= 70) {
                System.out.println("  " + score);
            }
        }

        System.out.println("\nFailing scores (< 70):");
        for (int score : scores) {
            if (score < 70) {
                System.out.println("  " + score);
            }
        }
    }
}

Output:

Passing scores (>= 70):
  95
  88
  72
  91
  85

Failing scores (< 70):
  67
  45

Example 2: ATM Menu

public class ATM {
    public static void main(String[] args) {
        int balance = 1000;
        int choice = 2;

        switch (choice) {
            case 1:
                System.out.println("Balance: $" + balance);
                break;
            case 2:
                int withdraw = 200;
                if (withdraw <= balance) {
                    balance -= withdraw;
                    System.out.println("Withdrawn: $" + withdraw);
                    System.out.println("New balance: $" + balance);
                } else {
                    System.out.println("Insufficient funds");
                }
                break;
            case 3:
                int deposit = 500;
                balance += deposit;
                System.out.println("Deposited: $" + deposit);
                System.out.println("New balance: $" + balance);
                break;
            default:
                System.out.println("Invalid option");
        }
    }
}

Output:

Withdrawn: $200
New balance: $800

Example 3: Number Guessing Game

public class GuessingGame {
    public static void main(String[] args) {
        int secretNumber = 7;
        int guess = 1;
        int attempts = 0;

        while (guess != secretNumber) {
            attempts++;

            if (guess < secretNumber) {
                System.out.println("Too low! Try again.");
            } else if (guess > secretNumber) {
                System.out.println("Too high! Try again.");
            }

            guess++;  // Next guess (simulated)
        }

        System.out.println("Correct! You guessed it in " + attempts + " attempts.");
    }
}

Output:

Too low! Try again.
Too low! Try again.
Too low! Try again.
Too low! Try again.
Too low! Try again.
Too low! Try again.
Too high! Try again.
Correct! You guessed it in 7 attempts.

Example 4: Nested Loops (Multiplication Table)

public class MultiplicationTable {
    public static void main(String[] args) {
        System.out.println("3x3 Multiplication Table:");

        for (int i = 1; i <= 3; i++) {  // Rows
            for (int j = 1; j <= 3; j++) {  // Columns
                System.out.print(i * j + "\t");  // \t is tab
            }
            System.out.println();  // New line after each row
        }
    }
}

Output:

3x3 Multiplication Table:
1	2	3
2	4	6
3	6	9

Common Mistakes to Avoid

Mistake 1: Infinite Loops

// WRONG: Condition never becomes false
while (true) {
    System.out.println("This runs forever");
    // Missing break or condition change
}

Fix: Ensure the condition can become false:

int count = 0;
while (count < 10) {
    System.out.println(count);
    count++;  // Eventually count >= 10
}

Mistake 2: Forgetting break in switch

// WRONG: Fall-through continues to next case
switch (day) {
    case 1:
        System.out.println("Monday");
        // Missing break!
    case 2:
        System.out.println("Tuesday");
        break;
}

// If day = 1, prints both "Monday" and "Tuesday"

Fix: Add break:

switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
}

Mistake 3: Off-by-One Errors

// WRONG: Iterates 6 times (0-5), not 5
for (int i = 0; i <= 5; i++) {
    System.out.println(i);
}

// Prints: 0, 1, 2, 3, 4, 5 (6 times)

Fix: Use < instead of <=:

for (int i = 0; i < 5; i++) {  // 0, 1, 2, 3, 4 (5 times)
    System.out.println(i);
}

Mistake 4: Using = Instead of == in Conditions

// WRONG: Assigns instead of compares
if (age = 18) {
    // ...
}

// Correct:
if (age == 18) {
    // ...
}

Mistake 5: Confusing continue and break

// WRONG: Meant to skip even numbers but exits loop
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        break;  // Exits entire loop (wrong!)
    }
    System.out.println(i);
}

// Output: (nothing, exits immediately)

// CORRECT: Skip even numbers
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip this iteration (right!)
    }
    System.out.println(i);
}

// Output: 1, 3, 5, 7, 9

Why This Matters

  • For logic: Control flow is where your program becomes intelligent. It makes decisions and repeats actions.
  • For algorithms: Every algorithm uses control flow. Sorting, searching, validation—all require conditionals and loops.
  • For user interaction: Your program responds to user input based on conditions. Games check if the player won. Forms validate if input is correct.
  • For efficiency: Loops prevent repetition. Instead of writing the same code 100 times, loop 100 times.
  • For real code: Professional programs are control flow. Every line of production code uses conditionals and loops.

Quick Cheat Sheet

Conditionals

IF:           if (condition) { ... }
IF-ELSE:      if (condition) { ... } else { ... }
IF-ELSE IF:   if (c1) { ... } else if (c2) { ... } else { ... }
SWITCH:       switch (value) { case 1: ... break; default: ... }

Loops

WHILE:        while (condition) { ... }
DO-WHILE:     do { ... } while (condition);
FOR:          for (init; condition; increment) { ... }
FOR-EACH:     for (type var : collection) { ... }

Loop Control

BREAK:        Exit loop immediately
CONTINUE:     Skip to next iteration

Decision Tree

Single condition?       → if-else
Multiple specific values? → switch (cleaner)
Multiple range checks?  → if-else if
Repeat N times?         → for
Repeat until condition? → while
Loop through collection? → for-each

In Summary

Control flow is what separates static lists of instructions from intelligent programs.

  • Conditionals let your program make decisions: "If the user is old enough, let them vote."
  • Loops let your program repeat: "Check every item in the list."

Together, they create powerful algorithms. Without them, you're just reading commands in order. With them, you're building logic.

Master control flow, and you can solve any programming problem.

Next up: New Chapter! Object Oriented Programming