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.
For Loop
Section titled “For Loop”The for loop is used when you know how many times you want to execute a block of code.
// Basic for loopfor (int i = 0; i < 5; i++) { System.out.println("Count: " + i);}While Loop
Section titled “While Loop”Executes a block of code as long as a condition is true.
int count = 0;while (count < 5) { System.out.println("Count: " + count); count++;}Do-While Loop
Section titled “Do-While Loop”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);Loop Control Statements
Section titled “Loop Control Statements”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);}Continue
Section titled “Continue”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}Infinite Loops
Section titled “Infinite Loops”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 loopfor (;;) { // Code to execute if (someCondition) { break; }}