Neural Sync Active
Control Flow in Java — Conditionals and Loops
Registry Synced
Control Flow in Java — Conditionals and Loops
2663 words
13 min read
Reading compass
Now · 🎯 Learning Objectives
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-elseandswitchexpressions - Use
for,while, anddo-whileloops 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
javaif (condition) { // Executes only if condition is true }
Rules:
- Condition must be a
booleanexpression (unlike Python where any value works) - Braces
{}are optional for single statements, but always use them — they prevent subtle bugs
javaint age = 18; if (age >= 18) { System.out.println("You can vote!"); }
2.2 if-else
javaint 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
javaint 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:javaint 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):
javaint 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:javaint 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:javaint 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):
javaString 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:
| Aspect | Traditional switch | Modern switch (14+) |
|---|---|---|
| Syntax | Colon + break | Arrow → syntax |
| Fall-through | Yes (must break) | No (automatic) |
| Multiple cases | Separate labels | Comma-separated |
| Returns a value | No (statement) | Yes (expression) |
| Scope | Each case shares scope | Each 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:
javaint count = 0; while (count < 5) { System.out.println("Count: " + count); count++; } // Output: // Count: 0 // Count: 1 // Count: 2 // Count: 3 // Count: 4
Structure:
javawhile (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:
javaint 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).
javaScanner 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:
javafor (initialization; condition; update) { // body }
- Initialization: Runs once at the start (
int i = 0) - Condition: Checked before each iteration (
i < 5) - Body: Executes if condition is true
- Update: Runs after each iteration (
i++) - Repeat steps 2-4 until condition is false Multiple variables:
javafor (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:
javaint[] 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:
javaint[] 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:
javafor (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:
javafor (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:
javaouter: // 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
| Situation | Best Loop | Example |
|---|---|---|
| Known number of iterations | for | "Sum numbers 1 to 100" |
| Unknown iterations, known condition | while | "Read until end of file" |
| Must execute at least once | do-while | "Menu-driven program" |
| Iterate over array/collection | for-each | "Process all elements" |
| Need index inside loop | for (traditional) | "Access arr[i]" |
6. Java vs Python: Control Flow
| Feature | Java | Python |
|---|---|---|
| Block delimiters | {} (braces) | Indentation |
| Condition | Must be boolean | Any truthy/falsy value |
else if | else if (two words) | elif |
| Switch | switch-case (traditional or expression) | None (use if-elif or dict) |
| For loop | for (init; condition; update) | for item in iterable: |
| For-each | for (Type var : collection) | for var in collection: (default) |
| While | while (condition) | while condition: |
| Break N loops | Labeled break | No built-in (use flags/functions) |
7. Common Pitfalls
Pitfall 1: Infinite Loops
javafor (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
javaint 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
javaint 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
javaint[] 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
javaList<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?javaint 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 becausex = 5is an assignment expression that returnsint(5), notboolean. 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?javafor (int i = 0; i < 5; i++) { if (i == 3) continue; System.out.print(i + " "); }Answer:0 1 2 4Wheni == 3,continueskipsSystem.out.print, so 3 is not printed. The loop continues withi = 4, theni = 5(condition fails, loop ends). Q3: What is the output of this switch?javaint 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 CSincex = 2, execution starts atcase 2:. It prints "B ", then falls through tocase 3:(no break), prints "C ", and hits thebreakwhich exits the switch. Q4: Write a loop that sums all even numbers from 1 to 100.Answer:javaint 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?javaouter: 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:pseudoi=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=2Wheni=1, j=1,continue outerskips to the next iteration of the outer loop (i=2). Note thati=1, j=1andi=1, j=2are never printed. Q6: Fix this infinite loopjavaint i = 0; while (i < 10) { System.out.println(i); }Answer: The loop is infinite becauseiis never incremented. Fix:javaint i = 0; while (i < 10) { System.out.println(i); i++; // or i = i + 1 }Q7: What is the output?javaint count = 0; do { System.out.print(count + " "); count++; } while (count < 0); System.out.println("\nDone");Answer:pseudo0 DoneThedo-whileloop always executes its body at least once, even though the conditioncount < 0is false from the start. Q8: Write a for loop that prints the multiplication table of 7 (1-10).Answer:javafor (int i = 1; i <= 10; i++) { System.out.println("7 × " + i + " = " + (7 * i)); }Output:pseudo7 × 1 = 7 7 × 2 = 14 ... 7 × 10 = 70Q9: What does this code print? Explain.javafor (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:pseudo0 is even --- 1 is odd --- 2 is even --- 3 is odd --- 4 is even ---Theelseclause only controls the FIRSTSystem.out.printlnafter it (since braces are omitted). The secondSystem.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:javaint 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); // SpringNote: Thedefaultcase is required for switch expressions to ensure all cases are covered (exhaustiveness).
📐 Key Concepts
| Statement | Purpose | Syntax |
|---|---|---|
if | Conditional branch | if (cond) { } |
if-else | Two-way branch | if (cond) { } else { } |
switch | Multi-way branch | switch (expr) { case v: } |
for | Count-controlled loop | for (init; cond; update) { } |
while | Condition-controlled loop | while (cond) { } |
do-while | Post-test loop | do { } while (cond); |
for-each | Array/collection iteration | for (Type v : coll) { } |
break | Exit loop/switch | break; / break label; |
continue | Skip to next iteration | continue; / continue label; |
🔗 Cross-References
- Next: OOP Concepts
- Arrays → week02/04-arrays.md
- Python Comparison: BSCS1002 — Control Flow in Python
- Reference: Oracle Java Tutorials — Control Flow Statements Join Discord Previous1.3 Memory ModelNext1.5 OOP Concepts