Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
764 views
in Blog Post by 48 54 93

In this post, we will discuss the different kinds of loops in Java for beginners.

What're Loops?

  • Loops mean repetition, looping back over the same block of code again and again.
  • A loop statement allows us to execute a statement or group of statements multiple times.
  • Loops can execute a block of code as long as a specified condition is reached.

Loops in Java

Java provides the following four types of loop to handle looping requirements:

  • While loop.
  • For loop.
  • Foreach loop.
  • Do / While Loop.

While Loop in Java

  • The while loop loops through a block of code as long as a specified condition is True.
  • When the condition becomes false, program control passes to the line immediately following the loop.

The syntax of While loop in Java

while(condition) {
   statement(s);
} 

While Loop In Java


For Loop in Java

  •  Use the For loop when you know exactly how many times you want to loop through a block of code.

The syntax of For loop in java 

for ( init; condition; increment ) {
   statement(s);
}
  • Init: is executed (one time) before the execution of the code block.
  • Condition: defines the condition for executing the code block.
  • Increment: is executed (every time) after the code block has been executed.

For Loop In Java


Foreach loop in Java

  • It iterates throw the items of the array and collections.

The syntax of Foreach loop in Java

for(data_type item : collection) {
    ...
}

In this example, we will use foreach statement that iterates over the array numbers to print its items.

foreach loop in java


Do / While Loop in Java

  • This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

The syntax of Do / While loop in Java 

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

Do/ While Loop in JAVA 


Conclusion

In this post, we have discussed the different types of loop in java and when we can use it.


If you don’t ask, the answer is always NO!
...