Module 4: Control Flow & LoopsBeginner22 min read
Loops (for, enhanced for, while, do-while) & Jump Statements
Iterate efficiently with for, for-each, while, and do-while loops, and control iteration with break, continue, and return.
Key Takeaways & Core Concepts
- `break`: Exits the innermost loop or
switch. With a label (outer: for (...)+break outer;), it can exit nested loops cleanly. - `continue`: Skips the rest of the current iteration and jumps to the loop condition/update.
- `return`: Exits the entire enclosing method immediately.
Introduction
Loops repeat a block of code until a termination condition is met. Choosing the right loop construct makes your intent immediately obvious to other developers.
Enhanced For-Each, While & Continue
1public class Main {
2 public static void main(String[] args) {
3 int[] nums = {10, 15, 20, 25, 30};
4 int oddSum = 0;
5 for (int n : nums) {
6 if (n % 2 == 0) continue;
7 oddSum += n;
8 }
9 System.out.println("Sum of odd numbers: " + oddSum);
10
11 int count = 3;
12 do {
13 System.out.println("Countdown: " + count);
14 count--;
15 } while (count > 0);
16 }
17}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
17 lines
Note: `continue` skips `10`, `20`, and `30`, summing only `15 + 25 = 40`.
Choosing the Right Loop
| Loop | Control Type | Best Used When |
|---|---|---|
for (init; cond; update) | Entry-controlled | You know the exact iteration count or need the index i |
for (Type item : collection) | Enhanced for-each | Reading every element of an array or Iterable cleanly |
while (cond) | Entry-controlled | Termination depends on a dynamic condition (e.g., reading until EOF) |
do { ... } while (cond); | Exit-controlled | Body must execute at least once (e.g., interactive CLI menus) |
Jump Statements & Labeled Breaks
- `break`: Exits the innermost loop or
switch. With a label (outer: for (...)+break outer;), it can exit nested loops cleanly. - `continue`: Skips the rest of the current iteration and jumps to the loop condition/update.
- `return`: Exits the entire enclosing method immediately.
Practice & AssessmentJava Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)