Verified for the 2025 AP Computer Science A exam•Citation:
The for loop is one of Java's most powerful and versatile iteration tools. While a while loop excels when the number of iterations is unknown, a for loop shines when you need to repeat code a specific number of times or iterate through collections of data. This study guide explores the structure, behavior, and applications of for loops, showing how they can make your code more efficient and readable when dealing with repetitive tasks.
The three components in the header serve specific purposes:
A for loop consists of three distinct parts enclosed in parentheses, followed by a block of code to be repeated:
for (initialization; conditional expression; incrementer) { // Code to be executed repeatedly (loop body) }
Understanding how a for loop executes is crucial:
The initialization statement executes once at the beginning
Before each iteration, the conditional expression is evaluated
After executing the loop body, the incrementer runs
The process repeats from step 2
This diagram illustrates the flow:
┌─────────────────┐ │ Initialization │ └────────┬────────┘ │ ▼ ┌─────────────────┐ false │ Conditional │─────────→ (Exit Loop) │ Expression │ └────────┬────────┘ │ true ▼ ┌─────────────────┐ │ Loop Body │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ Incrementer │ └────────┬────────┘ │ └─────────→
Let's see a simple example that uses System.out.println to display numbers:
// Print numbers from 1 to 5 for (int i = 1; i <= 5; i++) { System.out.println("Number: " + i); }
In this example:
int i = 1
initializes the counteri <= 5
is the conditional expression that continues the loop while i is less than or equal to 5i++
is the incrementer that adds 1 to i after each iterationOutput:
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
The initialization statement executes only once before the loop begins. It typically:
// Initialize a single variable for (int i = 0; i < 10; i++) { // Loop body } // Initialize multiple variables for (int i = 0, j = 10; i < j; i++, j--) { System.out.println("i = " + i + ", j = " + j); }
Important notes:
The conditional expression is a boolean expression that:
true
false
// Simple condition for (int i = 0; i < 10; i++) { // Executes 10 times (i from 0 to 9) } // Complex condition for (int i = 0; i < 100 && isPrime(i); i++) { // Executes until i reaches 100 or a non-prime number is found }
The incrementer executes after each iteration of the loop body. It typically:
// Standard increment for (int i = 0; i < 10; i++) { // i increases by 1 each time } // Decrement for (int i = 10; i > 0; i--) { // i decreases by 1 each time } // Custom step size for (int i = 0; i < 100; i += 10) { // i increases by 10 each time (0, 10, 20, ...) } // Multiple updates for (int i = 0, j = 10; i < j; i++, j--) { // i increases and j decreases each time }
for (int i = 1; i <= 10; i++) { System.out.println(i); } // Prints: 1 2 3 4 5 6 7 8 9 10
for (int i = 10; i >= 1; i--) { System.out.println(i); } // Prints: 10 9 8 7 6 5 4 3 2 1
// Even numbers from 2 to 10 for (int i = 2; i <= 10; i += 2) { System.out.println(i); } // Prints: 2 4 6 8 10
One of the most common uses of for loops is to traverse (iterate through) collections of data.
Arrays are fixed-size collections that store elements of the same type. A for loop can iterate through each element:
// Declare and initialize an array int[] numbers = {5, 10, 15, 20, 25}; // Traverse the array using a for loop for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + ": " + numbers[i]); }
An ArrayList is a resizable collection from Java's Collections Framework. It can also be traversed with a for loop:
import java.util.ArrayList; // Create and populate an ArrayList ArrayList<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); // Traverse the ArrayList for (int i = 0; i < names.size(); i++) { System.out.println("Name: " + names.get(i)); }
A while loop can always be rewritten as a for loop and vice versa. However, each has its strengths:
// While loop int i = 0; while (i < 10) { System.out.println(i); i++; } // Equivalent for loop for (int i = 0; i < 10; i++) { System.out.println(i); }
When to use each:
Any of the three components in a for loop can be empty:
// Initialization outside the loop int i = 0; for (; i < 10; i++) { // Loop body } // Incrementer inside the loop body for (int i = 0; i < 10;) { // Loop body i++; } // Condition checked inside (infinite loop with break) for (int i = 0;;i++) { if (i >= 10) { break; } // Loop body }
Java provides a simplified syntax for traversing collections called the "enhanced for loop" or "for-each loop":
int[] numbers = {5, 10, 15, 20, 25}; // Enhanced for loop for (int number : numbers) { System.out.println(number); }
This loop automatically iterates through each element without needing an explicit index.
"Off-by-one" errors occur when loop iterations are one too many or one too few:
// Prints 0 to 9 (10 numbers) for (int i = 0; i < 10; i++) { System.out.println(i); } // Prints 0 to 10 (11 numbers) - potential off-by-one error for (int i = 0; i <= 10; i++) { System.out.println(i); }
A for loop can become infinite if the conditional expression never evaluates to false:
// Infinite loop - i never changes for (int i = 0; i < 10;) { System.out.println("This will print forever"); } // Infinite loop - wrong direction for (int i = 0; i < 10; i--) { System.out.println("i is now " + i); }
Changing the loop variable inside the loop body can lead to unexpected behavior:
// Problematic: modifying i within the loop for (int i = 0; i < 10; i++) { System.out.println("Starting iteration with i = " + i); // Don't do this! i = i + 2; System.out.println("Ending iteration with i = " + i); }
int number = 5; int factorial = 1; for (int i = 1; i <= number; i++) { factorial *= i; } System.out.println("Factorial of " + number + " is " + factorial); // Output: Factorial of 5 is 120
int[] values = {28, 15, 92, 47, 63, 8}; int max = values[0]; // Start with the first element for (int i = 1; i < values.length; i++) { if (values[i] > max) { max = values[i]; } } System.out.println("Maximum value: " + max); // Output: Maximum value: 92
String pattern = ""; for (int i = 1; i <= 5; i++) { // Add i asterisks to the pattern for (int j = 0; j < i; j++) { pattern += "*"; } pattern += "\n"; // Add a newline } System.out.println(pattern); /* Output: * ** *** **** ***** */
In this section, we've explored the for loop, a powerful tool for controlled iteration in Java. For loops combine initialization, condition checking, and incrementing in a compact, readable format that clearly expresses the loop's intent and behavior. By mastering for loops, you'll be able to efficiently process data and perform repetitive tasks in your programs.