Skip to content
Büşra Oğuzoğlu edited this page Jul 3, 2022 · 28 revisions

Loops in Java:

1. While Loop:

  • In while loop, the loop-continuation-condition acts like an if statement. The loop will execute the statements repeatedly when the loop-continuation-condition is true.
  • In the loop body, we need to have an update statement that will eventually make the loop-continuation-condition false, so the loop will terminate.

Syntax:

while (loop-continuation-condition) 
{
    // Loop body
    statements;
}

2. Do-while Loop:

  • Unlike regular while loop, do-while loop it always executed at least once.

Syntax:

do { 
    // Loop body;
    statements;
} while (loop-continuation-condition);

3. For Loop:

Syntax:

4. For-each Loop:

  • We generally use this type of loop to iterate over the elements of a list of items. (Could be an ArrayList as an example)
  • If we want to keep track of the index, or we want to skip some elements, it is better to use normal for loop.

Syntax:

for (type var : array) 
{ 
    // Loop body
    statements using var;
}

It is same as this for loop:

for (int i=0; i<arr.length; i++) 
{ 
    // Loop body
    type var = arr[i];
    statements using var;
}

5. Nested Loops:

Clone this wiki locally