A loop is a kind of control statement.
Loops are used to decide how many times to execute another statement. There
are four kinds of loops in Java:
- while loops test whether a condition is true
before executing the controlled statement. This is the most flexible kind
of loop.
- do-while loops test whether a condition
is true after executing the controlled statement. These are the least frequently
used kind of loop; they are used when it is necessary to execute the controlled
statement at least once before it makes sense to test the condition.
for loops are (typically) used to execute the controlled statement
a given number of times. There are actually two kinds of for
loops:
- The original for loop, used when you need
to explicitly control the number of times the controlled statement is
executed. This is the most complicated kind of loop, but is very useful.
- The so-called "extended for loop,"
used when you want to execute the controlled statement once for every
element of an array or collection.