Loops in Java allow you to execute a block of code repeatedly based on a condition. In this tutorial, we’ll explore for
, while
, and do-while
loops.
for
LoopThe for
loop is great for running code a specific number of times:
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
while
LoopThe while
loop executes as long as its condition is true:
int count = 1;
while (count <= 3) {
System.out.println("Count: " + count);
count++;
}
do-while
LoopThe do-while
loop runs at least once, even if the condition is false:
int count = 1;
do {
System.out.println("Count: " + count);
count++;
} while (count <= 3);
break
and continue
Use break
to exit a loop and continue
to skip the current iteration:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Exit the loop
}
System.out.println(i);
}
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip this iteration
}
System.out.println(i);
}
Practice each loop type to understand when and where to use them. Loops are a fundamental tool for handling repetitive tasks in programming. Now you can learn about functions!