
In Java, there are several types of loops used to repeat a block of code. Each type serves different purposes based on the situation. The main types of loops in Java are:
1. for
Loop
The for
loop is typically used when you know in advance how many times you want to execute a block of code.
for (initialization; condition; update) {
// code to be executed
}
2. while
Loop
The while
loop continues executing as long as a given condition remains true
. It is used when the number of iterations is not predetermined.
Syntax
while (condition) {
// code to be executed
}
Example:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
3. do-while
Loop
The do-while
loop is similar to the while
loop, but it guarantees that the code block will execute at least once since the condition is checked after the loop’s body is executed.
do {
// code to be executed
} while (condition);
Example:
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
4. Enhanced for-each
Loop
The for-each
loop is used to iterate over arrays or collections, allowing easier access to elements without the need for indexing.
Syntax
for (type element : array/collection) {
// code to be executed
}
Example:
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}