What are the different loops available in java? How do we choose the right loop for a specific job? A loop is a set of statements that is supposed to repeat one or more times. Java supports 3 loops.
1. while loop – The block of statements will be repeated as long as the condition returns true. The condition should return false for exiting the loop. The ‘while’ loop can be used when the number of iterations are not certain.
2. do … while – Similar to the while loop. But the difference is – the iteration takes place at least for once. This is due to the condition that is placed at the end of body of the loop. The ‘do….while’ is apt when the loop certainly to execute at least for one time. For example, to display a menu with several options to select. When the user does not want to repeat, he should be given a provision soon after entering into the loop.
3. for loop – Use for loop when the number of the iterations are known before entering into the body of the loop. It has flexibility to assign variables before entering into the body of the loop and perform updation at the end of the loop.
4. for… each - Similar to for loop : perfectly apt for dealing with arrays. When each successive element is to be accessed, use this loop. The length or the indexes can not be used with this loop. Also useful to access a set of collections such as List, Set etc.