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:

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:

The for loop

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:

The for-each loop (enhanced for)

This loop is used to iterate arrays or Collection objects:

The two things you must remember about this loop are:

  • final is the only allowed modifier for element
  • You can’t use an pre-existing variable for element

Example:

Unreachable Code

Using false 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.


Leave a Reply