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.
The compiler first evaluates a boolean condition. If the 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 initial 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:
- for-each loops
Move on to the next exercise when you’re ready to learn how to build loops in Java.