GuidesJava basics
05 - Control Flow Loops
Learn how to repeat code efficiently using loops in Java
Loops let you repeat code without writing it over and over. They're essential for processing collections, generating worlds, and updating game objects.
While Loop
Repeats code while a condition is true:
int countdown = 5;
while (countdown > 0) {
System.out.println(countdown);
countdown--;
}
System.out.println("Blast off!");Structure
while (condition) {
// code to repeat
}Infinite Loops
Always make sure your loop condition will eventually become false, or your program will run forever!
int x = 0;
while (x < 10) {
System.out.println("Stuck!");
// Forgot to increase x!
}Do-While Loop
Like a while loop, but always runs at least once:
int health = 0;
do {
System.out.println("Attempting respawn...");
health = 100;
} while (health <= 0);For Loop
Best when you know how many times to repeat:
for (int i = 1; i <= 5; i++) {
System.out.println("Level " + i);
}Structure
for (initialization; condition; update) {
// code to repeat
}For Loop Parts
for (int i = 0; i < 10; i++) {
// ^ ^ ^
// Start Stop Step
}- Initialization: int i = 0 - Runs once at the start
- Condition: i < 10 - Checked before each loop
- Update: i++ - Runs after each loop
Break Statement
You can exit a loop early with break:
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // Exit loop when i is 6
}
System.out.println(i);
}Continue Statement
Skip to the next iteration with continue:
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i); // Prints only odd numbers
}Nested Loops
You can put loops inside other loops:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}Nested Loop Performance
Be careful with nested loops! They can slow down your mod significantly.
// This runs 1,000,000 times!
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
// Code here
}
}Try to avoid deeply nested loops when processing large amounts of data.