In Java, loops are used to execute a block of code repeatedly as long as a specified condition is met. There are several types of loops in Java, each suited to different types of tasks: for
, while
, do-while
, and enhanced for
loops.
for
LoopThe for
loop is used when the number of iterations is known beforehand. The syntax is:
for (initialization; condition; update) {
// code to be executed
}
For example:
for (int i = 0; i < 10; i++) {
System.out.println("i: " + i);
}
while
LoopThe while
loop is used when the number of iterations is not known and depends on a condition. The syntax is:
while (condition) {
// code to be executed
}
For example:
int i = 0;
while (i < 10) {
System.out.println("i: " + i);
i++;
}
do-while
LoopThe do-while
loop is similar to the while
loop, but it guarantees that the loop body is executed at least once. The syntax is:
do {
// code to be executed
} while (condition);
For example:
int i = 0;
do {
System.out.println("i: " + i);
i++;
} while (i < 10);
for
Loop (for-each Loop)The enhanced for
loop is used to iterate over arrays or collections. It’s simpler and more readable than a standard for
loop when dealing with collections. The syntax is:
for (type variableName : arrayOrCollection) {
// code to be executed
}
For example:
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println("number: " + number);
}
Loops can be nested inside other loops. Each loop will run its full course for every iteration of the outer loop.
For example:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}
break: Terminates the loop and transfers control to the statement immediately following the loop.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println("i: " + i);
}
continue: Skips the current iteration of the loop and proceeds with the next iteration.
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println("i: " + i);
}