Java loops : Types of loops in java


Very often we need to execute a group of statements repeatedly. Java loop statements are used to repeat the java statements number of times. Each repeated execution of statements is called as iteration. During each iteration, the value of some variable is altered and some condition is tested. This allows us to come out of the loop ultimately. If proper conditions and variable alteration is not used, you may end up in an infinite loop.

There are three types of java loops,
  1. for loop
  2. while loop
  3. do-while loop
  4. for-each

Along with loops you can use the java break and java continue statement.

Java break statement is used the break the execution of a java loop. The java break statement causes the control to pass out of the loop. Control will be transfer to the first statement after the closing curly brackets of the loop.

Java continue statement is used to skip a single iteration. When a continue statement is executed, it causes the flow of the control to the next iteration of the loop, skipping the current execution.

We can also use the nested loops and also can use the hybrid loop means like we can have a “while loop” inside “for loop” and so on.

Further to “for loop”, a new construct called for-each loop is available. This enhanced construct allows user to automatically work through the elements of a collection or an array.

Also see java for loop example, java for-each loop example, java while loop example and java do-while loop example.

No comments:

Post a Comment