Quiz 2

Control Flow in Java — Conditionals and Loops

2663 words
13 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Control Flow in Java — Conditionals and Loops ## 🎯 Learning Objectives By the end of this topic, you will be able to: - Write conditional branches using `if-else if-else` and `switch` expressions - Use `for`, `while`, and `do-while` loops correctly - Control loop behavior with `break`, `continue`, and labels - Ch...

Control Flow in Java — Conditionals and Loops

🎯 Learning Objectives

By the end of this topic, you will be able to:
  • Write conditional branches using if-else if-else and switch expressions
  • Use for, while, and do-while loops correctly
  • Control loop behavior with break, continue, and labels
  • Choose the right loop construct for different scenarios
  • Avoid common control flow errors like off-by-one and infinite loops

📋 Prerequisites

  • Data Types & Operators (02-data-types-operators.md): Boolean expressions, relational operators
  • BSCS1002 — Python: Python's if, for, while — but Java syntax differs significantly

1. Intuition: Your Code's Decision-Making

1.1 What Problem Does This Solve?

A program without control flow is just a straight line — every statement executes once, in order. Real programs need to:
  • Branch: "If the user is logged in, show the dashboard; otherwise, show the login page."
  • Repeat: "Process every item in this list."
  • Exit early: "Stop processing once we find what we're looking for." Control flow statements give your program the ability to make decisions and repeat tasks.

1.2 Mental Model: Road Intersections

(Diagram) Think of if as a fork in the road with a sign that says "Free WiFi → this way, No WiFi → that way". while loops are roundabouts — you go around until your exit appears.

2. Conditional Statements

2.1 if Statement

java
if (condition) {
    // Executes only if condition is true
}
Rules:
  • Condition must be a boolean expression (unlike Python where any value works)
  • Braces {} are optional for single statements, but always use them — they prevent subtle bugs
java
int age = 18;
if (age >= 18) {
    System.out.println("You can vote!");
}

2.2 if-else

java
int temperature = 30;
if (temperature > 35) {
    System.out.println("It's hot outside!");
} else {
    System.out.println("It's pleasant outside.");
}

2.3 if-else if-else Chain

java
int score = 85;
char grade;
if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else if (score >= 70) {
    grade = 'C';
} else if (score >= 60) {
    grade = 'D';
} else {
    grade = 'F';
}
System.out.println("Grade: " + grade);  // Grade: B
Important: The order matters! Conditions are evaluated top-to-bottom, and the first matching branch executes.

2.4 Ternary Operator — ? :

A shorthand for if-else that returns a value:
java
int x = 10;
String result = (x > 5) ? "Greater" : "Less or equal";
//                ↑          ↑           ↑
//           condition    true value   false value
System.out.println(result);  // "Greater"
Nested ternary (avoid when complex):
java
int a = 5, b = 10, c = 3;
int max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
// Hard to read! Use if-else instead.

2.5 switch Statement

switch is ideal for checking a single variable against many possible values:
java
int day = 3;
String dayName;
switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    case 6:
        dayName = "Saturday";
        break;
    case 7:
        dayName = "Sunday";
        break;
    default:
        dayName = "Invalid day";
        break;
}
System.out.println(dayName);  // Wednesday
Critical: The break Statement Without break, execution falls through to the next case:
java
int month = 2;
switch (month) {
    case 1:
        System.out.println("January");
    case 2:
        System.out.println("February");  // ← starts here
    case 3:
        System.out.println("March");      // ← but also executes this!
        break;
}
// Output:
// February
// March
This is called fall-through — it's sometimes intentional, but often a bug. Java 14+ Switch Expressions (modern syntax):
java
String result = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    case 4 -> "Thursday";
    case 5 -> "Friday";
    case 6, 7 -> "Weekend";  // Multiple values
    default -> "Invalid";
};
System.out.println(result);  // Wednesday
Comparison:
AspectTraditional switchModern switch (14+)
SyntaxColon + breakArrow syntax
Fall-throughYes (must break)No (automatic)
Multiple casesSeparate labelsComma-separated
Returns a valueNo (statement)Yes (expression)
ScopeEach case shares scopeEach case is its own scope

3. Loops — Repeating Actions

3.1 while Loop

Use when you don't know in advance how many iterations you need:
java
int count = 0;
while (count < 5) {
    System.out.println("Count: " + count);
    count++;
}
// Output:
// Count: 0
// Count: 1
// Count: 2
// Count: 3
// Count: 4
Structure:
java
while (condition) {
    // body — executes as long as condition is true
}
// Continues here when condition becomes false

3.2 do-while Loop

Guaranteed to execute at least once — the condition is checked after each iteration:
java
int count = 0;
do {
    System.out.println("Count: " + count);
    count++;
} while (count < 5);
// Same output as while loop
When to use: When you need to execute the body before checking (e.g., reading user input, menu-driven programs).
java
Scanner scanner = new Scanner(System.in);
int choice;
do {
    System.out.println("1. Option A  2. Option B  3. Exit");
    choice = scanner.nextInt();
    // Process choice...
} while (choice != 3);

3.3 for Loop

Use when you know exactly how many times to iterate:
java
// Basic for loop
for (int i = 0; i < 5; i++) {
    System.out.println("i = " + i);
}
// i = 0, i = 1, i = 2, i = 3, i = 4
Structure breakdown:
java
for (initialization; condition; update) {
    // body
}
  1. Initialization: Runs once at the start (int i = 0)
  2. Condition: Checked before each iteration (i < 5)
  3. Body: Executes if condition is true
  4. Update: Runs after each iteration (i++)
  5. Repeat steps 2-4 until condition is false Multiple variables:
java
for (int i = 0, j = 10; i < j; i++, j--) {
    System.out.println("i = " + i + ", j = " + j);
}

3.4 Enhanced for-each Loop

Used specifically for iterating over arrays and collections:
java
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
    System.out.println(num);
}
// 10, 20, 30, 40, 50
Cannot modify the array through the enhanced for loop:
java
int[] arr = {1, 2, 3};
for (int val : arr) {
    val = 99;  // Only changes local variable, NOT the array
}
System.out.println(Arrays.toString(arr));  // [1, 2, 3]

4. Loop Control: break and continue

4.1 break

Exits the loop immediately:
java
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;  // Exit loop when i reaches 5
    }
    System.out.print(i + " ");
}
// Output: 0 1 2 3 4

4.2 continue

Skips the rest of the current iteration, moving to the next:
java
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip even numbers
    }
    System.out.print(i + " ");
}
// Output: 1 3 5 7 9

4.3 Labeled break and continue

Used to break out of nested loops:
java
outer:  // Label
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        if (i == 1 && j == 1) {
            break outer;  // Exits BOTH loops
        }
        System.out.println("i=" + i + ", j=" + j);
    }
}
// Output:
// i=0, j=0
// i=0, j=1
// i=0, j=2
// i=1, j=0
// (breaks before i=1, j=1)

5. Choosing the Right Loop

SituationBest LoopExample
Known number of iterationsfor"Sum numbers 1 to 100"
Unknown iterations, known conditionwhile"Read until end of file"
Must execute at least oncedo-while"Menu-driven program"
Iterate over array/collectionfor-each"Process all elements"
Need index inside loopfor (traditional)"Access arr[i]"

6. Java vs Python: Control Flow

FeatureJavaPython
Block delimiters{} (braces)Indentation
ConditionMust be booleanAny truthy/falsy value
else ifelse if (two words)elif
Switchswitch-case (traditional or expression)None (use if-elif or dict)
For loopfor (init; condition; update)for item in iterable:
For-eachfor (Type var : collection)for var in collection: (default)
Whilewhile (condition)while condition:
Break N loopsLabeled breakNo built-in (use flags/functions)

7. Common Pitfalls

Pitfall 1: Infinite Loops

java
for (int i = 0; i < 10; i--) {  // i-- instead of i++
    System.out.println(i);
}
// i goes: 0, -1, -2, ... never reaches 10!
Why: Off-by-one in the update expression causes the condition to never be met. Fix: i++ not i--.

Pitfall 2: Using = Instead of == in Conditions

java
int x = 5;
if (x = 10) {  // Compile error! x = 10 is assignment, not comparison
}
Why: In Java, = is assignment and returns a value (not boolean), so the compiler catches this. In C/C++, this is a common bug. Fix: Use == for comparison.

Pitfall 3: Forgetting break in switch

java
int value = 2;
switch (value) {
    case 1: System.out.println("One");
    case 2: System.out.println("Two");   // ← starts here
    case 3: System.out.println("Three"); // ← also executes!
}
// Output: Two Three (fall-through)
Why: Traditional switch falls through to the next case unless you break. Fix: Add break after each case, or use switch expressions (Java 14+).

Pitfall 4: Off-by-One Errors

java
int[] arr = {10, 20, 30};
for (int i = 0; i <= arr.length; i++) {  // <= instead of <
    System.out.println(arr[i]);  // Index 3 → ArrayIndexOutOfBoundsException!
}
Why: Arrays are 0-indexed, so valid indices are 0 to length-1. Fix: Use i < arr.length (not <=).

Pitfall 5: Modifying Collection During For-Each

java
List<String> list = new ArrayList<>();
list.add("A"); list.add("B"); list.add("C");
for (String s : list) {
    if (s.equals("B")) {
        list.remove(s);  // ConcurrentModificationException!
    }
}
Why: For-each uses an iterator internally; modifying the collection concurrently throws an exception. Fix: Use Iterator with iterator.remove(), or collect items to remove and do it after the loop.

8. Practice Questions

Q1: What is the output of this code?
java
int x = 10;
if (x = 5) {
    System.out.println("Five");
}
System.out.println("Done");
Answer: The code does not compile. In Java, if (x = 5) is illegal because x = 5 is an assignment expression that returns int (5), not boolean. In C/C++ this would be a runtime bug (always true), but Java's type system catches it at compile time. Q2: What is the output?
java
for (int i = 0; i < 5; i++) {
    if (i == 3) continue;
    System.out.print(i + " ");
}
Answer: 0 1 2 4
When i == 3, continue skips System.out.print, so 3 is not printed. The loop continues with i = 4, then i = 5 (condition fails, loop ends). Q3: What is the output of this switch?
java
int x = 2;
switch (x) {
    case 1:
        System.out.print("A ");
    case 2:
        System.out.print("B ");
    case 3:
        System.out.print("C ");
        break;
    default:
        System.out.print("D ");
}
Answer: B C
Since x = 2, execution starts at case 2:. It prints "B ", then falls through to case 3: (no break), prints "C ", and hits the break which exits the switch. Q4: Write a loop that sums all even numbers from 1 to 100.
Answer:
java
int sum = 0;
for (int i = 2; i <= 100; i += 2) {
    sum += i;
}
System.out.println("Sum of evens: " + sum);
// Alternative approach:
int sum2 = 0;
for (int i = 1; i <= 100; i++) {
    if (i % 2 == 0) {
        sum2 += i;
    }
}
Both compute 2550. Q5: What does this code print?
java
outer:
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        if (i == 1 && j == 1) {
            continue outer;
        }
        System.out.println("i=" + i + " j=" + j);
    }
}
Answer:
pseudo
i=0 j=0
i=0 j=1
i=0 j=2
i=1 j=0
i=2 j=0
i=2 j=1
i=2 j=2
When i=1, j=1, continue outer skips to the next iteration of the outer loop (i=2). Note that i=1, j=1 and i=1, j=2 are never printed. Q6: Fix this infinite loop
java
int i = 0;
while (i < 10) {
    System.out.println(i);
}
Answer: The loop is infinite because i is never incremented. Fix:
java
int i = 0;
while (i < 10) {
    System.out.println(i);
    i++;  // or i = i + 1
}
Q7: What is the output?
java
int count = 0;
do {
    System.out.print(count + " ");
    count++;
} while (count < 0);
System.out.println("\nDone");
Answer:
pseudo
0
Done
The do-while loop always executes its body at least once, even though the condition count < 0 is false from the start. Q8: Write a for loop that prints the multiplication table of 7 (1-10).
Answer:
java
for (int i = 1; i <= 10; i++) {
    System.out.println("7 × " + i + " = " + (7 * i));
}
Output:
pseudo
7 × 1 = 7
7 × 2 = 14
...
7 × 10 = 70
Q9: What does this code print? Explain.
java
for (int i = 0; i < 5; i++) {
    if (i % 2 == 0) {
        System.out.println(i + " is even");
    } else
        System.out.println(i + " is odd");
        System.out.println("---");
}
Answer:
pseudo
0 is even
---
1 is odd
---
2 is even
---
3 is odd
---
4 is even
---
The else clause only controls the FIRST System.out.println after it (since braces are omitted). The second System.out.println("---") always executes because it's NOT part of the else block. Always use braces {} even for single statements! Q10: Write a switch expression (Java 14+) that returns "Spring", "Summer", "Fall", or "Winter" based on a month number.
Answer:
java
int month = 3;  // March
String season = switch (month) {
    case 12, 1, 2 -> "Winter";
    case 3, 4, 5 -> "Spring";
    case 6, 7, 8 -> "Summer";
    case 9, 10, 11 -> "Fall";
    default -> "Invalid month";
};
System.out.println(season);  // Spring
Note: The default case is required for switch expressions to ensure all cases are covered (exhaustiveness).

📐 Key Concepts

StatementPurposeSyntax
ifConditional branchif (cond) { }
if-elseTwo-way branchif (cond) { } else { }
switchMulti-way branchswitch (expr) { case v: }
forCount-controlled loopfor (init; cond; update) { }
whileCondition-controlled loopwhile (cond) { }
do-whilePost-test loopdo { } while (cond);
for-eachArray/collection iterationfor (Type v : coll) { }
breakExit loop/switchbreak; / break label;
continueSkip to next iterationcontinue; / continue label;

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.