Foundation
05 โ Loops
Previous: 04 Control Flow ยท Next: 06 Methods
โถ๏ธ java pkg1core/core6Loops.java
for loop โ when you need an index
1for (int i = 0; i < 5; i++) {2 System.out.print(i + " ");3}4// 0 1 2 3 4Three parts: init โ condition โ update.
Enhanced for (for-each)
1int[] nums = {10, 20, 30};2for (int n : nums) {3 System.out.println(n);4}๐ก Use for-each when you need each element, not the index.
while loop
1int count = 3;2while (count > 0) {3 System.out.println(count);4 count--;5}Checks condition before each iteration. May run zero times.
do-while loop
1int x = 0;2do {3 System.out.println("Runs at least once");4} while (x > 0);Body runs at least once, then checks condition.
break and continue
1for (int i = 1; i <= 10; i++) {2 if (i % 2 == 0) continue; // skip evens3 if (i > 7) break; // stop loop4 System.out.print(i + " ");5}6// 1 3 5 7| Keyword | Effect |
|---|---|
break |
Exit the loop entirely |
continue |
Skip to next iteration |
Labeled break (nested loops)
1outer:2for (int i = 1; i <= 5; i++) {3 for (int j = 1; j <= 5; j++) {4 if (i + j == 7) {5 break outer; // exits both loops6 }7 }8}Use sparingly โ often a method extraction is clearer.
Which loop to choose?
| Loop | Best for |
|---|---|
for |
Known iterations, need index |
for-each |
Iterate every element |
while |
Unknown iterations, condition-driven |
do-while |
Must run at least once (menus, input validation) |
Practice
- Run
core6Loops. - Print multiplication table 1โ10 with nested for loops.
- Sum array elements with for-each.
Next โ 06 Methods Related โ 01 Core Java
Source named in this chapter
- core6Loopspkg1core/core6Loops.java