Skip to content

Loops

This content is for Java. Switch to the latest version for up-to-date documentation.

Loops allow you to execute a block of code repeatedly.

The for loop is used when you know how many times you want to execute a block of code.

// Basic for loop
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}

Executes a block of code as long as a condition is true.

int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}

Similar to while loop, but guarantees at least one execution of the code block.

int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 5);

Terminates the loop immediately.

for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
System.out.println(i);
}

Skips the current iteration and continues with the next iteration.

for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i); // Only prints odd numbers
}

An infinite loop is a loop that keeps running forever because the exit condition never becomes true or is missing entirely. This can happen if you forget to update the loop variable, use the wrong condition, or intentionally create a loop that never ends.

// Infinite for loop
for (;;) {
// Code to execute
if (someCondition) {
break;
}
}
Built with passion by Ngineer Lab