Loop Statements in Java | for, while , for-each loops in Detail

 

What are the Loops in Java?


Loop statements in Java are used to repeatedly execute a block of code. 


The most commonly used loop statements are:


1. while loop: The while loop repeatedly executes a block of code as long as a certain condition is true. The syntax for the while loop is:


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


For example:


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




2. do-while loop: The do-while loop is similar to the while loop, but it guarantees that the block of code will be executed at least once before the condition is checked. 


The syntax for the do-while loop is:


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


For example:


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




3. for loop: The for loop is used to execute a block of code a specific number of times. 


The syntax for the for loop is:


for (initialization; condition; increment/decrement) {
 
   // code to be executed
 
}


For example:


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




4. for-each loop: The for-each loop is used to iterate over arrays or collections. 


The syntax for the for-each loop is:


for (data_type variable : array/collection) {
 
   // code to be executed
 
}


For example:


int[] numbers = {1, 2, 3, 4, 5};
 
for (int number : numbers) {
 
   System.out.println(number);
 
}



In summary, loop statements are used in Java to repeatedly execute a block of code. The while loop repeatedly executes a block of code as long as a certain condition is true.

Post a Comment

Post a Comment (0)

Previous Post Next Post