
Loops repeat code. Print a message ten times. Process every item in a list. Keep asking for input until the user gets it right. Without loops, you’d copy and paste the same code over and over.
Java has three main loop types. Each fits different situations.
The for Loop
Use a for loop when you know how many times to repeat.
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}
Output:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
The for loop has three parts inside the parentheses, separated by semicolons:
Initialization: int i = 0 runs once before the loop starts. It creates a counter variable.
Condition: i < 5 is checked before each iteration. If true, the loop body runs. If false, the loop ends.
Update: i++ runs after each iteration. It changes the counter.
The loop above runs five times. The variable i starts at 0, and the loop continues while i is less than 5.
Counting Variations
Start at 1 instead of 0:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
// Prints 1, 2, 3, 4, 5
Count down:
for (int i = 5; i > 0; i--) {
System.out.println(i);
}
// Prints 5, 4, 3, 2, 1
Count by twos:
for (int i = 0; i <= 10; i += 2) {
System.out.println(i);
}
// Prints 0, 2, 4, 6, 8, 10
Looping Through Arrays
A common use of for loops is processing arrays:
String[] names = {"Alice", "Bob", "Charlie"};
for (int i = 0; i < names.length; i++) {
System.out.println("Hello, " + names[i]);
}
Output:
Hello, Alice
Hello, Bob
Hello, Charlie
The condition i < names.length ensures you don’t go past the end of the array. Array indices start at 0, and the last valid index is length - 1.
The Enhanced for Loop (for-each)
When you need every element in an array or collection and don’t care about the index, the enhanced for loop is cleaner.
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
System.out.println("Hello, " + name);
}
Read it as “for each name in names.” The variable name takes on each value in the array, one at a time.
The enhanced for loop works with arrays and any class that implements Iterable, including ArrayList, HashSet, and other collections.
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum: " + sum); // Sum: 150
Use the enhanced for loop when you don’t need the index. Use the traditional for loop when you need to know which position you’re at or need to modify the array.
The while Loop
Use a while loop when you don’t know in advance how many times to repeat. The loop continues as long as a condition is true.
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
This produces the same output as the for loop example. The difference is structural: while loops are better when the number of iterations depends on something other than counting.
Reading Until a Condition
A typical while loop pattern:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
String input = "";
while (!input.equals("quit")) {
System.out.print("Enter command (quit to exit): ");
input = scanner.nextLine();
System.out.println("You entered: " + input);
}
System.out.println("Goodbye!");
This loop continues until the user types “quit.” You can’t know in advance how many times that will take.
Infinite Loops
If the condition never becomes false, the loop runs forever.
// Infinite loop - runs forever
while (true) {
System.out.println("This never stops");
}
Sometimes infinite loops are intentional, with a break statement to exit. More often they’re bugs caused by forgetting to update the condition.
int x = 0;
// Bug: x is never incremented
while (x < 10) {
System.out.println(x);
// Missing: x++;
}
If your program hangs, check your loop conditions and updates.
The do-while Loop
A do-while loop runs the body first, then checks the condition. It always executes at least once.
int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 5);
The output is identical to the while version. The difference appears when the condition is false from the start:
int x = 10;
// while version - never runs
while (x < 5) {
System.out.println("while: " + x);
}
// do-while version - runs once
do {
System.out.println("do-while: " + x);
} while (x < 5);
Output:
do-while: 10
The while loop checks first, finds 10 < 5 is false, and never enters the body. The do-while loop runs the body first, prints 10, then checks the condition and exits.
When to Use do-while
Use do-while when you need the body to run at least once. A common case is input validation:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
} while (number <= 0);
System.out.println("You entered: " + number);
You need to ask for input at least once before you can check if it’s valid.
break and continue
Two keywords control loop execution from inside the body.
break
The break statement exits the loop immediately.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
Output:
0
1
2
3
4
When i reaches 5, break exits the loop. The remaining iterations never run.
A common pattern is searching for a value:
String[] names = {"Alice", "Bob", "Charlie", "Diana"};
String target = "Charlie";
int foundIndex = -1;
for (int i = 0; i < names.length; i++) {
if (names[i].equals(target)) {
foundIndex = i;
break; // No need to keep looking
}
}
if (foundIndex >= 0) {
System.out.println("Found at index: " + foundIndex);
} else {
System.out.println("Not found");
}
continue
The continue statement skips the rest of the current iteration and moves to the next one.
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}
Output:
1
3
5
7
9
When i is even, continue skips the println and moves to the next iteration. Only odd numbers get printed.
Nested Loops
Loops can contain other loops.
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 4; col++) {
System.out.print(row + "," + col + " ");
}
System.out.println();
}
Output:
1,1 1,2 1,3 1,4
2,1 2,2 2,3 2,4
3,1 3,2 3,3 3,4
The outer loop runs 3 times. For each outer iteration, the inner loop runs 4 times. Total iterations of the inner body: 3 x 4 = 12.
Nested loops are common for working with two-dimensional data like tables, grids, or matrices.
Multiplication Table
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Choosing the Right Loop
for loop: You know how many iterations. Counting through a range. Processing arrays by index.
enhanced for loop: You need every element in a collection. You don’t need the index.
while loop: You don’t know how many iterations. The condition depends on something that changes unpredictably.
do-while loop: Same as while, but you need at least one execution. Input validation is the classic case.
Practical Example
Here’s a program that finds prime numbers:
public class PrimeFinder {
public static void main(String[] args) {
int limit = 50;
System.out.println("Prime numbers up to " + limit + ":");
for (int num = 2; num <= limit; num++) {
boolean isPrime = true;
// Check if num is divisible by any number from 2 to sqrt(num)
for (int divisor = 2; divisor * divisor <= num; divisor++) {
if (num % divisor == 0) {
isPrime = false;
break; // No need to check more divisors
}
}
if (isPrime) {
System.out.print(num + " ");
}
}
System.out.println();
}
}
Output:
Prime numbers up to 50:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Common Mistakes
Off-by-one errors. Using <= when you meant <, or starting at 1 when the array starts at 0. These cause missing items or ArrayIndexOutOfBoundsException.
String[] items = {"a", "b", "c"};
// Bug: tries to access items[3] which doesn't exist
for (int i = 0; i <= items.length; i++) {
System.out.println(items[i]);
}
// Correct
for (int i = 0; i < items.length; i++) {
System.out.println(items[i]);
}
Infinite loops. Forgetting to update the variable that controls the condition.
Modifying a collection while iterating. Removing items from an ArrayList while looping through it causes ConcurrentModificationException. Use an Iterator or loop backward.
Wrong loop type. Using a for loop when you don’t know the count, or a while loop for simple counting. Match the loop to the problem.
What’s Next
Loops often need user input to control their behavior. The next tutorial covers the Scanner class for reading keyboard input and processing user responses.
Related: Java Conditionals: if, else, switch | Getting User Input with Scanner
Sources
- Oracle. “The for Statement.” The Java Tutorials. docs.oracle.com
- Oracle. “The while and do-while Statements.” The Java Tutorials. docs.oracle.com


