3. Control Flow: Ifs & Loops | Java Course - Study Chapter | QuizMaker

Direct the execution of your code dynamically.

Read
18m
Type
Chapter
Access
Free

Course

Java Programming: From Zero to Enterprise

Topic

1. Java Fundamentals

[!NOTE] Programs rarely execute straight from top to bottom. You need decision-making logic and repeat logic to build anything useful. Welcome to Control Flow.

IF-Else Statements

The most basic form of decision making. You evaluate a boolean expression, and execute a block of code if it is true.

int speed = 80;

if (speed > 70) {
    System.out.println("You are speeding! Ticket issued.");
} else if (speed > 40) {
    System.out.println("Good pace. Safe driving.");
} else {
    System.out.println("You are driving too slow.");
}

The Switch Statement

If you have many else if conditions checking the same variable against specific, strict values, use a switch block to dramatically improve readability and performance.

int dayOfWeek = 3;

switch(dayOfWeek) {
    case 1:
        System.out.println("Monday");
        break; // Crucial! Prevents "falling through" to the next case.
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Weekend!");
}

Loops: Automating Repetition

When you need to execute the same logic multiple times, use a loop. Java provides several types depending on your needs.

1. The For Loop

Use a for loop when you know exactly how many times you want to iterate through a block of code.

// 1. Initialize counter (int i = 0); 2. Check condition (i < 5); 3. Increment (i++)
for (int i = 0; i < 5; i++) {
  // This will print 0, 1, 2, 3, 4
  System.out.println("Iteration count: " + i);
}

2. The While Loop

Use a while loop when the number of iterations is unknown and deeply reliant on a dynamic condition. It checks the condition before running.

int counter = 0;
while (counter < 3) {
    System.out.println(counter);
    counter++; // If you forget this, the loop runs forever!
}

3. The Do-While Loop

A do-while loop is similar to a while loop, but it evaluates its condition at the end of the block instead of the beginning. This guarantees the code block will be executed at least once, even if the condition is false from the start.

int pass = 0;
do {
    System.out.println("This runs once no matter what!");
    pass++;
} while (pass < 0); // Condition is false, loop terminates after 1 run.

[!CAUTION] Infinite Loops: Always double-check your loop conditions. An infinite while (true) loop without a break statement will freeze your application entirely and cause a catastrophic CPU spike.

Writing Conditions That Stay Readable

Control flow becomes hard when conditions try to do too much in one line. A clean Java program usually gives complex decisions a meaningful name before using them in an if statement.

int age = 21;
boolean hasVerifiedEmail = true;
boolean isEligible = age >= 18 && hasVerifiedEmail;

if (isEligible) {
    System.out.println("Account can be activated");
}

This style is easier to debug because you can print or inspect isEligible directly. It also reads closer to the business rule.

Loop Choice Guide

NeedUseExample
Known number of iterationsforPrint 1 to 10
Unknown count, condition-firstwhileRead until valid input
Run at least oncedo-whileShow a menu once before asking again
Visit every itemEnhanced forPrint every name in an array

Guard Clauses

Sometimes it is cleaner to handle invalid cases early instead of nesting multiple levels of if.

static void printDiscount(int age) {
    if (age < 0) {
        System.out.println("Invalid age");
        return;
    }

    if (age >= 60) {
        System.out.println("Senior discount");
    } else {
        System.out.println("Standard price");
    }
}

Common Mistakes

Mini Practice

Write a program that prints grades from marks: 90+ A, 75+ B, 60+ C, otherwise D. Then rewrite it using named boolean variables such as isExcellent and isGood.

Practice Lab: Grade and Eligibility Checker

Use conditions and loops together in one small program.

  1. Create an array of five marks.
  2. Loop through each mark.
  3. Print Pass for marks 40 and above, otherwise Fail.
  4. Add grade bands: A for 90+, B for 75+, C for 60+, D for 40+.
  5. Count how many students passed.

Goal: Practice if, else if, comparison operators, and loop repetition in one flow.

Revision Checkpoint

Before the quiz: Identify whether a problem needs a decision, a counted loop, or a condition-based loop.

Open on QuizMaker