There are four kinds of loops in Java:
- The
while
loop - The
do-while
loop - The
for
loop - The for-each loop (enhanced
for
)
The while loop
It’s executed while the given expression is evaluated to true
:
1 2 3 4 |
while (expression) statement_or_block |
If the expression is initially false
, the statement or block is never executed.
The do-while loop
It’s always executed at least once and keeps executing while the given expression is evaluated to true
:
1 2 3 4 5 |
do statement_or_block while (expression); |
The for loop
1 2 3 4 |
for ([initialization_expr]; [termination_expr]; [increment_expr]) statement_or_block |
The four things you must remember about this loop are:
- The initialization expression is executed just once, as the loop begins
- When the termination expression evaluates to
false
, the loop terminates - The increment expression is invoked after each iteration. This expression can only be
++
,--
, an assignment (=
), a method invocation or an object creation - All 3 expressions are optional:
1 2 3 4 5 |
// infinite loop example for ( ; ; ) { } |
The for-each loop (enhanced for)
This loop is used to iterate arrays or Collection
objects:
1 2 3 4 |
for (type element : collection) statement_or_block |
The two things you must remember about this loop are:
final
is the only allowed modifier forelement
- You can’t use an pre-existing variable for
element
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// iterating an array int[] numbers = {1,2,3}; for (int i : numbers) { System.out.println(i); } // iterating a collection ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); for (Integer e : list) { System.out.println(e); } |
Unreachable Code
Usingfalse
as the evaluation expression for a loop has different consequences depending on the kind of loop. Expect questions related to this topic in the exam:
Loop | Result |
---|---|
while (false) { … } |
Compiler error |
do { … } while (false); |
Ok. The code block is executed once |
for (…; false; …) { … } |
Compiler error |
To complete your preparation about Java loops, read the lesson about break and continue.