break: leave the loop now
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i * i > 50) {
System.out.println("First square over 50: " + i + " x " + i + " = " + (i * i));
break;
}
}
}
}Output
First square over 50: 8 x 8 = 64
continue: skip to the next round
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue;
}
System.out.print(i + " ");
}
System.out.println();
}
}Output
1 2 4 5 7 8 10
Multiples of 3 are skipped: continue jumps straight to the next i.
Think of it like this:
breakis walking out of the cinema.continueis skipping one advert but staying for the film.
Loops inside loops
A loop can contain another loop. The inner loop runs completely for each round of the outer loop:
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 4; row++) {
for (int star = 1; star <= row; star++) {
System.out.print("*");
}
System.out.println();
}
}
}Output
* ** *** ****
Row 1 prints 1 star, row 2 prints 2 stars, and so on. The println() after the inner loop starts a new row.
Remember:
breakonly leaves the innermost loop it is in.