Skip to content
Büşra Oğuzoğlu edited this page Jul 4, 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.
  • While loop is generally used when the number of repetitions is not fixed. (Example: Continue until getting a certain input from the user)

Syntax:

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

2. Do-while Loop:

  • Unlike regular while loop, do-while loop it always executed at least once, since loop body is executed before the loop-continuation-condition is evaluated.
  • while statement behaves the same way as the regular while loop.
  • while and do-while loops can be easily converted but using one or the other can be beneficial in some scenarios.

Syntax:

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

3. For Loop:

  • A for loop is generally used when we want to iterate over a list of elements or the number of repetitions is known in advance. (Example: If you want to write "Hello World" for 100 times, or if you have a list to iterate over, you already know the number of repetitions.)
  • You can convert a for loop to a while loop, but sometimes using one over the other is easier. When we want to iterate over an index or want to count, a for loop provides a more compact version of a while loop, therefore it is preferred.

Syntax:

for (initial-action; loop-continuation-condition; 
    action-after-each-iteration) {
    // Loop body;
    statements;
}

Example:

Code that prints numbers from 1 to 10:

for(int i=1;i<=10;i++){  
    System.out.println(i);  
}

It can be converted to a while loop:

initial-action;
while (loop-continuation-condition) {
    // Loop body;
    statements;
    action-after-each-iteration;
}

More precisely, these two loops are interchangable:

for (i = initialValue; i < endValue; i++) {
    // Loop body
    statements;
}
i = initialValue; // Initialize loop control variable 
while (i < endValue) {
    // Loop body
    statements;
    i++; // Adjust loop control variable
}

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:

  • If a loop exists inside the loop body of another loop, it's called a nested loop.

Syntax:

// outer loop
for (int i = 1; i <= 5; ++i) {
  // codes

  // inner loop
  for(int j = 1; j <=2; ++j) {
    // codes
  }
..
}

Example:

Code that prints a half pyramid:

for(int i=1;i<=5;i++){  
    for(int j=1;j<=i;j++){  
        System.out.print("* ");  
}  

Output:

* 
* * 
* * * 
* * * * 
* * * * *

6. Break & Continue:

break keyword inside the loop is used to break the loop (even though the loop is supposed to continue according to the condition)

for (int i = 0; i < 10; i++) {
    // Terminate the loop when i is 5
    if (i == 5)
        break;
}

continue keyword inside the loop is used for skipping, as an example:

for (int i = 0; i < 10; i++) {
    // If the number is 2
    // skip and continue
    if (i == 2)
        continue;
}

7. Infinite Loops:

Infinite loops can be useful in a small number of scenarios, however, they are often caused by errors in our program. We generally want to avoid making our loops infinite.

Infinite for loop:

for(;;){  
    //code to be executed  
} 

Infinite while loop:

while(true){
    //code to be executed
}

Infinite do-while loop:

do{
    //code to be executed
}while(true);

Summary: Which loop to use?

  • If the number of iterations is fixed, for loop is a simple and readable option and it is used most commonly in this scenario.
  • If we do not know how many times we want to execute the loop body, or if it is bound to a condition other than a count, while loop is recommended.
  • If we decide to use while loop over the for loop but we need to execute the loop body at least once, we can use do-while loop.
Clone this wiki locally