The labs on this site need JavaScript to run. The same content is written out below.
Learn › Java › Basic syntax
Conditionals and loops
How many times does a loop run, and where does it stop?
Why it exists — To do the same thing ten times or a hundred times without a loop, you would have to copy the same line that many times, and a number of repetitions that is known only when the program runs, such as the length of a list or user input, cannot be written down at all. A loop lets you write the code to repeat only once and leaves the number of repetitions to the condition expression, so the same code handles a different amount of data.
Where it's used today — It is used to go through the items of a list one by one to compute a total, to stop with break when the first item that matches a condition is found, and to ask again until valid input arrives. When the number of repetitions is fixed, for is mainly used, and when you do not know in advance when it will end, while is mainly used. To go through the elements of a collection in order, the for-each statement (for (String s : list)), which needs no index, or a stream is sometimes used.
A loop repeats "check the condition → body → change the value" until the condition becomes false. Whether you write < or <= in the condition changes the number of iterations by one, and break and continue cut that flow short or skip part of it. switch is a conditional statement: like if, it chooses what to run based on a value. It jumps to the case whose value matches, and if there is no break, execution continues into the cases below.
Checked against real execution · Checked by running 24 combinations on JDK 21 (the two combinations that never end were observed for 2 seconds)
Concepts in this lab
- for statement and while statement
- These are loops, which execute the same code repeatedly while a condition is true. while (condition) { body } checks the condition, executes the body if it is true, and goes back to the condition, and it ends when the condition becomes false. for (initialization; condition; increment) { body } does the same thing, but gathers on one line the code that declares and changes the variable used for the loop. The order of execution of a for statement is initialization (once), condition, body, increment, and then the condition again. Starting from 0, writing i < n makes the loop run n times and writing i <= n makes it run n + 1 times, so a single comparison operator in the condition changes the count by one.
- break and continue
- Why it exists — Without break, to end a loop partway you have to keep a separate variable that marks "found it" and put it in the condition. break and continue end the loop right there or skip only the current iteration, so they change the flow without such a marker variable.
- Where it's used today — They are used like this: when reading a file line by line, skip an empty line with continue, and stop reading with break when a line that means the end comes. To end even the outer loop at once in a nested loop, put a label before the outer loop and write break label;.
- These are statements that change the flow of a loop partway through. break ends, right there, the innermost loop or switch that encloses it. continue does not end the loop. It skips only the remaining code of the current iteration and then moves on to the next iteration. In a for statement, continue goes to the condition check after the increment part has been executed, but in a while statement it goes straight to the condition check. So in a while statement, if the code that changes the value is below the continue, the loop may never end.
- switch statement and fall through
- Why it exists — To compare one value with several cases, you have to chain a long if and else if and write the same variable again each time. switch lets you write the value to compare once and list a case for each, so a branch with many paths can be read at a glance.
- Where it's used today — It is used where what to do depends on a few fixed values, such as a menu number, a day of the week, or an enum constant. Unless you intentionally want two cases to run the same code one after the other, the arrow (->) form, where you need not worry about forgetting break, is safer.
- A switch is a statement that compares one value with several cases and jumps to the matching case to execute from there. If no case matches, control goes to default. In the form that uses a colon, as in case 1:, execution continues into the code of the cases below until it reaches a break, and this is called fall through. Leaving out a break does not cause a compile-time error, so it is an easy mistake to make. The case 1 -> form (the arrow), which is available from Java 14, executes only the code of the matching case, so no break is needed.
Try these
- Default settings — A for statement written with i <= 3. It runs four times, not three.
- Changing to < — i < 3 runs three times, for 0, 1, and 2.
- Reaching a break — The whole loop ends when i is 1.
- Reaching a continue — Only the iteration in which i is 1 is skipped, and the loop goes on.
- continue in a while statement — The code is the same, and yet it never ends.
- Removing break from a switch — Execution starts at case 2 and goes through every case below it.
- A switch with arrows — Only the matching case is executed, even though no break is written.
Running with the default settings
- int i = 0: This is the first part inside the parentheses of the for statement (the initialization). It is executed only once, at the very beginning, and i becomes 0.
- Checking i <= 3: i is 0, and 0 <= 3 is true. The body is entered.
- System.out.println(i): The value of i is printed. The output is 0.
- i++: When the body ends, the third part inside the parentheses of the for statement (the increment) is executed. The value of i is now 1. Control goes back to the condition check.
- Checking i <= 3: i is 1, and 1 <= 3 is true. The body is entered.
- System.out.println(i): The value of i is printed. The output is 1.
- i++: When the body ends, the third part inside the parentheses of the for statement (the increment) is executed. The value of i is now 2. Control goes back to the condition check.
- Checking i <= 3: i is 2, and 2 <= 3 is true. The body is entered.
- System.out.println(i): The value of i is printed. The output is 2.
- i++: When the body ends, the third part inside the parentheses of the for statement (the increment) is executed. The value of i is now 3. Control goes back to the condition check.
- Checking i <= 3: i is 3, and 3 <= 3 is true. <= is true when the two are equal as well, so the body is entered one more time.
- System.out.println(i): The value of i is printed. The output is 3.
- i++: When the body ends, the third part inside the parentheses of the for statement (the increment) is executed. The value of i is now 4. Control goes back to the condition check.
- Checking i <= 3: i is 4, and 4 <= 3 is false. The body is not entered, and the loop ends.
- System.out.println("done"): The line after the loop is executed. The body was entered 4 times in all.
Result of this run
- i <= 3 is true when i is 3 as well, so it runs one more time than i < 3. Starting from 0, i < n runs n times and i <= n runs n + 1 times. Mistakes like this, in which the count is off by one, are very common. To loop over an array with n elements, use i < n.
- A for statement is a loop that gathers the initialization, the condition, and the increment on one line. The order of execution is initialization (once) → condition → body → increment → condition → ... .
Code
// Only the lines inside main are shown (class, main declaration, and imports omitted)
for (int i = 0; i <= 3; i++) { // initialization; condition; increment
System.out.println(i);
}
System.out.println("done");
Assumptions of this model
The output and the counts of the 24 combinations (12 loops and 12 switch statements) were checked against the result of running code with the same structure on JDK 21 in our test environment. The number of times the body was entered was obtained by putting counting code on the first line of the body in the program used for the check. For the two combinations that use continue in a while statement, it was confirmed that the real program does not end after 2 seconds and keeps repeating only the body. That the program "never ends" cannot itself be proved by execution. It is a conclusion that follows from the structure of the code, in which i does not change. The model decides that there is an infinite loop, and stops, when control comes back to the condition check with the same value of i. It was also confirmed by execution that a switch without a default executes nothing when it is given a value that matches no case. The switch with arrows has been a standard part of the language since Java 14. The do-while statement, the enhanced for statement (for-each), switch expressions that produce a value, and the labeled break are not covered.
Previous lab: Operators and type conversion · Next lab: Arrays