Looping statements can execute a block of code as long as a specified condition is reached
The different looping statements available in java
The while statement
The while statement continually executes a block of code while a particular condition is true
Syntax
Program:
do-while statement
do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once
Syntax
Program:
public class Usecase {
For statement
> The for statement provides a compact way to iterate over a range of values and it repeatedly loops until a particular condition is satisfied
> The initialization expression initializes the loop once it is executed as the loop begins.
> When the termination expression evaluates to false, the loop terminates.
> The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
Syntax
Program:
For-each Loop
for-each loop is used to iterate the array/collection class. It is referred to as for each because it iterates through each element of the array.
It uses the same keyword for like for loop, Instead of declaring and initializing a loop counter variable, we should declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name
Syntax
Program:
Output:
> It is not appropriate when you want to modify the array
> It does not keep track of the index. So we cannot obtain an array index using the For-Each loop
> It only iterates forward over the array in single steps
> It cannot process two decision-making statements at once