Repeating Yourself with Loops
Let Java do the boring repeating for you
Loops let your program repeat a block of code without you having to type it out over and over. Anytime you find yourself doing the same thing again and again, a loop is probably the answer.
The while loop
A while loop keeps running its block of code as long as a condition stays true:
int count = 1;
while (count <= 5) {
System.out.println(count);
count++;
}
This prints the numbers 1 through 5, one per line. Each time through the loop, count goes up by one, until it reaches 6, at which point count <= 5 becomes false and the loop stops.
The for loop
A for loop packs the starting point, the condition, and the update step all onto one line, which makes counting loops especially tidy:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
This does exactly the same thing as the while loop example above, just written more compactly. Many Java developers reach for a for loop whenever they know in advance how many times they want to repeat something.
Looping through a range of tasks
Loops are not just for printing numbers. You could use one to check every item in a list, add up a series of prices, or repeat a game turn until a player wins.
int total = 0;
for (int i = 1; i <= 10; i++) {
total = total + i;
}
System.out.println(total);
That loop adds up the numbers from 1 to 10 and prints the final total, 55.
Loops, together with if and else, give your programs the power to react and repeat, which is most of what makes code feel genuinely useful rather than just a list of one time instructions.
Quick check
Q1 What is it called when a loop's condition never becomes false and it runs forever?
Q2 Which loop packs the starting point, condition, and update step onto one line?
Want to save your progress? It's free.
Create a free account