You know what is boring? Doing the same thing over and over. You know what computers are great at? Doing the same thing over and over. That is what loops are for.
Loops let you repeat a block of code as many times as you want. Java gives you three kinds of loops, and each one has its own superpower.
The for Loop
The for loop is the most common one. Use it when you know exactly
how many times you want to repeat something. It has three parts in the parentheses:
initialization, condition, and update.
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}
This prints "Count: 0" through "Count: 4". The loop starts with i = 0,
runs as long as i < 5, and adds 1 to i after each round.
The while Loop
Use while when you are not sure how many times you need to loop.
It just checks a condition before each iteration and keeps going as long as
the condition is true.
int i = 0;
while (i < 5) {
System.out.println("i is " + i);
i++;
}
This does the same thing as the for loop above. The difference is that the condition is checked at the start. If it is false from the beginning, the code inside never runs at all.
The do-while Loop
The do-while loop is like while, but with a twist โ it checks the
condition at the end. That means the code inside always runs at least once.
int i = 0;
do {
System.out.println("i is " + i);
i++;
} while (i < 5);
Notice the semicolon at the end of the while line. Beginners forget that all the time.
When to Use Which?
Here is the simple rule:
- for โ when you know the exact number of iterations (looping through an array, counting to ten)
- while โ when you are waiting for a condition to change (user input, reading a file until the end)
- do-while โ when you need the code to run at least once no matter what (menu systems, game loops)