Coding for All
Lesson 21: Break
Break Escape from a loop with break.
1public static void main(String[] args) {
2 int i = 0;
3 while (true) {
4 System.out.println(i);
5 i++;
6 if (i == 5) {
7 break;
8 }
9 }
10}
Terminal
$ javac Main.java
$ java Main
0
1
2
3
4
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 (true) {
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. while (true) would repeat forever, because the condition is always true! We will need break to escape.
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 the counter: 0, 1, 2, 3, 4.
i++;
i++ increases i by 1. It is a short way of writing i = i + 1; (you can also write i += 1;).
if (i == 5) {
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. Once the counter reaches 5, it is time to stop.
break;
break immediately stops the loop it is inside, jumping to the code after the loop's closing brace. Without it, this while (true) loop would run forever.
}
This } closes the if block.
}
This } closes the while loop.
}
This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.