Core Java

core6Loops

Path
pkg1core/core6Loops.java
Package
pkg1core
Study order
5
Run
Single-file source launch
Command
java pkg1core/core6Loops.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core6Loops.java
1package pkg1core;2 3/*4 * core6Loops.java5 * ----------6 * for, enhanced for (for-each), while, do-while, labels, break, continue.7 *8 * EXPLANATION:9 *  - Use a classic `for` when you need the index.10 *  - Use for-each to iterate elements cleanly.11 *  - `break`/`continue` can target a labeled loop to control nesting.12 */13public class core6Loops {14    public static void main(String[] args) {15        // Classic for16        System.out.print("for: ");17        for (int i = 1; i <= 5; i++) System.out.print(i + " ");18        System.out.println();19 20        // for-each over an array21        int[] nums = {10, 20, 30};22        System.out.print("for-each: ");23        for (int n : nums) System.out.print(n + " ");24        System.out.println();25 26        // while27        System.out.print("while countdown: ");28        int c = 3;29        while (c > 0) { System.out.print(c + " "); c--; }30        System.out.println();31 32        // do-while (body runs at least once)33        int x = 0;34        do { System.out.println("do-while runs once even though x=" + x); } while (x > 0);35 36        // continue: skip even numbers37        System.out.print("odd numbers: ");38        for (int i = 1; i <= 10; i++) {39            if (i % 2 == 0) continue;40            System.out.print(i + " ");41        }42        System.out.println();43 44        // Labeled break: exit nested loops at once45        System.out.println("labeled break (find first pair summing to 7):");46        outer:47        for (int i = 1; i <= 5; i++) {48            for (int j = 1; j <= 5; j++) {49                if (i + j == 7) {50                    System.out.println("  found i=" + i + " j=" + j);51                    break outer;52                }53            }54        }55    }56}