Loops (For, While)
Overview
Loops allow you to execute a block of code multiple times without duplicating the code. This is essential for iterating over arrays, processing lists of users, or keeping a game running until the player quits.
There are three primary loops in Core Java: 1. For Loop: Best used when you know EXACTLY how many times you want to iterate (e.g., counting from 1 to 10). 2. While Loop: Best used when you don't know the exact count, but want to loop UNTIL a dynamic condition becomes false (e.g., waiting for a user to type 'exit'). 3. Do-While Loop: Similar to a while loop, but it guarantees the code will execute at least once, because the condition is checked at the end of the block instead of the beginning.
Syntax
The for loop neatly packages the counter, condition, and increment logic onto a single line. The while loop requires you to manually manage your counters inside the block.
public class Main {
public static void main(String[] args) {
// 1. The For Loop
// Initializer; Condition; Iterator
for (int i = 1; i <= 5; i++) {
System.out.println("For Count: " + i);
}
// 2. The While Loop
int countdown = 3;
while (countdown > 0) {
System.out.println("While Countdown: " + countdown);
countdown--; // MUST update condition manually!
}
// 3. The Do-While Loop
int attempt = 1;
do {
System.out.println("Executing Attempt: " + attempt);
attempt++;
} while (attempt < 1); // Condition is false, but it ran once!
}
}Common Pitfalls
- Infinite Loops. If you create a
whileloop and forget to update the condition variable inside the block (e.g., forgettingcountdown--;), the condition will remain true forever, instantly freezing the program and crashing the CPU. - Off-by-one errors. Using
i <= array.lengthinstead ofi < array.lengthin a for loop will cause anArrayIndexOutOfBoundsExceptionon the very last iteration.
Interview Questions
break and continue inside a loop?break completely terminates the loop immediately, destroying it. continue only skips the current iteration, immediately jumping back to the top of the loop to start the next cycle.
while loop over a for loop?When the number of iterations is unknown and depends on external factors, such as reading lines from a network stream until the stream closes, or continuously prompting a user for input until they provide valid data.
Real-World Example
A video game's core architecture runs on an infinite while loop known as the 'Game Loop'. It continuously updates player positions and renders graphics 60 times a second until the user hits quit.
public void startGame() {
boolean isPlaying = true;
while(isPlaying) {
processInput();
updatePhysics();
renderGraphics();
if (userHitsQuit()) {
isPlaying = false; // Breaks the loop naturally
}
}
}Check Your Knowledge
Test your understanding of Loops (For, While) with these quick questions.