Java Loops
Loops repeat code. for is for a known count, while for "until something changes", and the enhanced for walks through a collection.
ExampleJava
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.println("for " + i);
}
int n = 3;
while (n > 0) {
System.out.println("while " + n);
n--;
}
int[] nums = {10, 20, 30};
for (int x : nums) {
System.out.println("each " + x);
}
for (int i = 0; i < 10; i++) {
if (i == 2) continue; // skip 2
if (i == 4) break; // stop at 4
System.out.println("i=" + i);
}
}
}Output
for 1 for 2 for 3 while 3 while 2 while 1 each 10 each 20 each 30 i=0 i=1 i=3
Quick check
Which statement leaves a loop immediately?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.