In the programming world, we hate repeating ourselves. There are two reasons for this:
- Writing the same code over and over is time-consuming.
- Having less code means having less to debug.
But we often need to do the same task more than once. Fortunately, computers are really good (and fast) at doing repetitive tasks. And in Java, we can use loops.
A loop is a programming tool that allows developers to repeat the same block of code until some condition is met.
First, a starting condition is evaluated. If the starting condition is
true, then the loop body is executed. When the last line of the loop body is executed, the condition is re-evaluated. This process continues until the condition is
false (if the condition never becomes
false, we can actually end up with an infinite loop!). If the starting condition is
false, the loop never gets executed.
We employ loops to easily scale programs - saving time and minimizing mistakes.
We’ll go over three types of loops that we’ll see everywhere:
Move on to the next exercise when you’re ready to learn how to build loops in Java.