Coding for All
Lesson 22: Continue
Continue Skip one trip around a loop with continue.
1public static void main(String[] args) {
2 int i = 0;
3 while (i < 5) {
4 i++;
5 if (i == 3) {
6 continue;
7 }
8 System.out.println(i);
9 }
10}
Terminal
$ javac Main.java
$ java Main
1
2
4
5
Every line, explained
public static void main(String[] args) {
Every Java program starts at the main method. When you run the program, Java looks for this exact line, public static void main(String[] args), and runs everything between its { and } from top to bottom.
int i = 0;
int declares a variable that stores a whole number (an "integer") like 1, 5 or 1000. The = sign stores the value on the right into the variable named on the left, and the semicolon ; ends the statement, like a full stop at the end of a sentence.
while (i < 5) {
A while loop repeats its block for as long as the condition in the parentheses is true. The condition is checked again before every trip around the loop. This loop runs while i is less than 5.
i++;
i++ increases i by 1. It is a short way of writing i = i + 1; (you can also write i += 1;).
if (i == 3) {
if checks the condition inside its parentheses. If the condition is true, Java runs the code between the { and }. If it is false, Java skips that code completely. We single out the moment the counter hits 3.
continue;
continue skips the rest of this trip around the loop and jumps straight back to the condition check. When i is 3, the println below is skipped, so 3 never appears in the output.
}
This } closes the if block.
System.out.println(i);
System.out.println(...) prints whatever is inside the parentheses to the terminal, then moves to a new line. Read the name carefully: print-l-n is short for "print line". Prints 1, 2, 4 and 5, but not 3, because continue skipped past this line that time.
}
This } closes the while loop.
}
This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.