Java For Loop ā Syntax, Flow, Examples & Best Practices
Everything you need to know about Java For Loop ā syntax, flow diagram, entry-controlled behavior, difference from while loop, enhanced for loop, array traversal, nested for loops, break, continue, anti-patterns, and real-world production code examples.
Last Updated
March 2026
Read Time
20 min
Level
Beginner to Intermediate
Chapter
6 of 35
What is a For Loop in Java?
A for loop in Java is an entry-controlled loop ā it checks a boolean condition before executing the loop body. If the condition is false on the very first check, the body never executes. The for loop is the most commonly used loop in Java because it keeps all loop control information ā initialization, condition, and update ā in one compact header, making it highly readable and predictable.
Java provides three loop types: for (best when iteration count is known), while (condition checked before body ā best for unknown count), and do-while (body executes first ā best for at-least-once scenarios). The for loop shines when you know exactly how many times to iterate ā traversing an array, printing a multiplication table, iterating over a range of numbers, or processing a fixed-size collection.
Java 5 introduced the enhanced for loop (also called for-each), which further simplifies iterating over arrays and collections by eliminating the index variable entirely. Both forms are covered in depth in this guide ā along with nested loops, labeled break/continue, infinite for loops, and production-grade usage patterns.
For Loop ā Syntax & Execution Flow
The for loop header has three parts separated by semicolons: initialization, condition, and update. Each part is optional ā you can omit any or all of them ā but both semicolons are always required. The body follows in curly braces.
for (initialization; condition; update) { // body ā executes while condition is true } Three header parts: (1) Initialization ā runs ONCE before the loop starts. Typically declares and sets the loop variable: int i = 0. (2) Condition ā a boolean expression checked BEFORE each iteration. If false, loop exits. If omitted, treated as always true (infinite loop). (3) Update ā runs AFTER each iteration body. Typically increments or decrements: i++, i--, i+=2. Any or all parts can be omitted, but both semicolons (;;) are always required. No semicolon after the closing parenthesis ā unlike do-while.
Step 1: Execute initialization (runs once only ā at the very start). Step 2: Evaluate the condition. Step 3: If condition is FALSE ā exit the loop; execute next statement after the loop. Step 4: If condition is TRUE ā execute the loop body. Step 5: Execute the update statement. Step 6: Go back to Step 2. Key insight: initialization runs exactly once. The condition is checked before every iteration ā including the very first. If condition is false from the start, the body never executes (0 iterations). This is the entry-controlled nature of the for loop.
for: initialization; condition; update are all in the header ā compact and self-contained. Best when iteration count is known. while: initialization is before the loop, condition is in the header, update is inside the body ā more spread out. Best when iteration count is unknown or condition is event-driven. The for loop is syntactic sugar for a while loop: for(int i=0; i<n; i++){body} is exactly equivalent to: int i=0; while(i<n){body; i++;}. Choose for loop when the iteration count or range is evident from the loop header itself ā it communicates intent more clearly to readers.
public class ForLoopSyntax {
public static void main(String[] args) {
// ā
Basic for loop ā print 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
// Output: Count: 1 through Count: 5
// Note: i is NOT accessible here ā scoped inside the for header
// ā
Decrement loop ā countdown from 5
for (int i = 5; i >= 1; i--) {
System.out.print(i + " "); // 5 4 3 2 1
}
System.out.println();
// ā
Step of 2 ā even numbers
System.out.print("Even: ");
for (int i = 2; i <= 20; i += 2) {
System.out.print(i + " "); // 2 4 6 8 10 12 14 16 18 20
}
System.out.println();
// ā
KEY DEMO: condition FALSE from start ā body NEVER runs
System.out.print("Never prints: ");
for (int i = 10; i < 5; i++) {
System.out.print(i); // This never executes
}
System.out.println("(nothing)");
// ā
Variable declared BEFORE loop ā accessible outside
int j;
for (j = 0; j < 3; j++) {
System.out.print(j + " "); // 0 1 2
}
System.out.println("j after loop: " + j); // j = 3 ā accessible!
// ā
Multiple variables in initialization and update
for (int a = 0, b = 10; a < b; a++, b--) {
System.out.print("(" + a + "," + b + ") "); // (0,10) (1,9) (2,8) (3,7) (4,6)
}
System.out.println();
// ā
Sum of numbers 1 to 100
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("Sum 1 to 100 = " + sum); // 5050
// ā
Omitting update ā update inside body
for (int i = 1; i <= 5; ) {
System.out.print(i + " ");
i++; // Update inside body
}
System.out.println();
}
}For Loop Examples ā Common Patterns
These examples cover the most frequently used for loop patterns in Java ā from number processing and series generation to character printing and accumulator patterns. Each demonstrates why the for loop is the natural choice for known-count iteration.
public class ForLoopExamples {
public static void main(String[] args) {
// ā
Example 1: Multiplication table
int table = 7;
System.out.println("--- Table of " + table + " ---");
for (int i = 1; i <= 10; i++) {
System.out.printf("%d x %2d = %2d%n", table, i, table * i);
}
// ā
Example 2: Factorial
int n = 6;
long factorial = 1;
for (int i = 2; i <= n; i++) {
factorial *= i;
}
System.out.println(n + "! = " + factorial); // 720
// ā
Example 3: Check prime number
int num = 29;
boolean isPrime = num > 1;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
System.out.println(num + " is prime: " + isPrime); // true
// ā
Example 4: Fibonacci series up to n terms
int terms = 10;
int a = 0, b = 1;
System.out.print("Fibonacci: ");
for (int i = 1; i <= terms; i++) {
System.out.print(a + " ");
int temp = a + b;
a = b;
b = temp;
}
System.out.println();
// Output: 0 1 1 2 3 5 8 13 21 34
// ā
Example 5: Sum of even numbers 1 to 50
int evenSum = 0;
for (int i = 2; i <= 50; i += 2) {
evenSum += i;
}
System.out.println("Sum of even 1-50: " + evenSum); // 650
// ā
Example 6: Reverse a string using for loop
String original = "TechSustainify";
StringBuilder reversed = new StringBuilder();
for (int i = original.length() - 1; i >= 0; i--) {
reversed.append(original.charAt(i));
}
System.out.println("Reversed: " + reversed); // yfiniatsuShceT
// ā
Example 7: Count vowels in a string
String text = "Java Programming Language";
int vowelCount = 0;
String vowels = "aeiouAEIOU";
for (int i = 0; i < text.length(); i++) {
if (vowels.indexOf(text.charAt(i)) != -1) {
vowelCount++;
}
}
System.out.println("Vowels in '" + text + "': " + vowelCount); // 8
// ā
Example 8: Power of a number without Math.pow
int base = 3, exponent = 5;
long result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}
System.out.println(base + "^" + exponent + " = " + result); // 243
// ā
Example 9: Print all prime numbers from 1 to 50
System.out.print("Primes 1-50: ");
for (int i = 2; i <= 50; i++) {
boolean prime = true;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) { prime = false; break; }
}
if (prime) System.out.print(i + " ");
}
System.out.println();
// Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
// ā
Example 10: GCD of two numbers using for loop
int x = 48, y = 36;
int gcd = 1;
for (int i = 1; i <= Math.min(x, y); i++) {
if (x % i == 0 && y % i == 0) {
gcd = i;
}
}
System.out.println("GCD(" + x + ", " + y + ") = " + gcd); // 12
}
}For Loop vs While Loop ā Key Differences
Both for and while are entry-controlled loops ā they check the condition before executing the body. The difference is structural and semantic: the for loop bundles initialization, condition, and update in one header; the while loop separates them. The choice communicates intent to every future reader of your code.
public class ForLoopVsWhile {
public static void main(String[] args) {
// ā
Known count ā for loop is cleaner
System.out.print("for (known count): ");
for (int i = 1; i <= 5; i++) {
System.out.print(i + " "); // 1 2 3 4 5
}
System.out.println();
// Same with while ā more verbose
System.out.print("while (known count): ");
int i = 1; // Initialization before loop
while (i <= 5) {
System.out.print(i + " "); // 1 2 3 4 5
i++; // Update inside body
}
System.out.println();
// ā
Unknown count ā while is more natural
// Read digits of a number until none remain
int number = 98765;
System.out.print("Digits (while, natural): ");
while (number > 0) {
System.out.print(number % 10 + " ");
number /= 10;
}
System.out.println();
// Same with for ā awkward empty init section
int num2 = 98765;
System.out.print("Digits (for, awkward): ");
for (; num2 > 0; num2 /= 10) {
System.out.print(num2 % 10 + " ");
}
System.out.println();
// ā
Variable scope difference ā important!
for (int x = 0; x < 3; x++) { }
// System.out.println(x); // ā COMPILE ERROR ā x not accessible here
int y = 0;
while (y < 3) { y++; }
System.out.println("y after while: " + y); // ā
y = 3 ā accessible
// ā
For loop with continue ā update still runs (unlike while!)
System.out.print("for continue: ");
for (int k = 1; k <= 5; k++) {
if (k == 3) continue; // Skips body but k++ in header STILL runs
System.out.print(k + " "); // 1 2 4 5 ā 3 skipped, no infinite loop
}
System.out.println();
// while with continue ā must update BEFORE continue or infinite loop!
System.out.print("while continue (safe): ");
int m = 0;
while (m < 5) {
m++; // Update BEFORE continue ā critical!
if (m == 3) continue;
System.out.print(m + " "); // 1 2 4 5
}
System.out.println();
}
}Enhanced For Loop (For-Each) ā Clean Collection Iteration
The enhanced for loop (introduced in Java 5) provides a concise, readable way to iterate over arrays and any class that implements Iterable (List, Set, Map values, etc.). It eliminates index management entirely ā no initialization, no condition, no update. Just element by element, from first to last.
Use enhanced for (for-each) when: (1) You need every element in order from first to last. (2) You do not need the index of each element. (3) You do not need to modify the array/collection during iteration. (4) You want clean, readable code that communicates 'process each element.' Perfect for: printing all elements, summing values, finding max/min, filtering, checking conditions across all elements. The enhanced for loop is the preferred idiom in modern Java code for array and collection traversal.
Do NOT use enhanced for when: (1) You need the index ā use traditional for(int i=0; i<arr.length; i++). (2) You need to modify array elements ā the loop variable is a copy (for primitives) or reference copy (for objects), not the actual slot. (3) You need to iterate in reverse. (4) You need to skip elements by index. (5) You need to iterate two arrays in parallel (two indices). (6) You need to remove elements from a List while iterating ā use Iterator.remove() or removeIf(). In all these cases, fall back to the traditional for loop or Iterator.
For primitive arrays (int[], double[]), the loop variable is a copy of each value. Changing it does NOT change the array: for(int x : arr) { x = 0; } ā the array is unchanged. For object arrays (String[], MyClass[]), the loop variable is a reference copy ā you can call mutating methods on the object, but reassigning the variable (element = new MyClass()) does NOT affect the array. To truly modify array elements, use a traditional for loop with the index: arr[i] = newValue.
import java.util.*;
public class EnhancedForLoop {
public static void main(String[] args) {
// ā
Enhanced for with int array
int[] numbers = {10, 20, 30, 40, 50};
System.out.print("Elements: ");
for (int num : numbers) {
System.out.print(num + " "); // 10 20 30 40 50
}
System.out.println();
// ā
Sum using enhanced for
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum: " + sum); // 150
// ā
Enhanced for with String array
String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
// ā
Enhanced for with ArrayList
List<String> cities = new ArrayList<>(List.of("Delhi", "Mumbai", "Bangalore", "Hyderabad"));
System.out.println("Cities:");
for (String city : cities) {
System.out.println(" - " + city);
}
// ā
Enhanced for with 2D array ā outer loop
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println("Matrix:");
for (int[] row : matrix) { // Each row is an int[]
for (int val : row) { // Each value in the row
System.out.printf("%3d", val);
}
System.out.println();
}
// ā
Find max using enhanced for
int[] scores = {85, 92, 78, 96, 88};
int max = scores[0];
for (int score : scores) {
if (score > max) max = score;
}
System.out.println("Max score: " + max); // 96
// ā Enhanced for does NOT modify primitive array
int[] arr = {1, 2, 3};
for (int x : arr) {
x = x * 10; // Modifies copy ā arr is UNCHANGED
}
System.out.println("arr[0] after attempt: " + arr[0]); // Still 1
// ā
Correct way to modify ā use traditional for with index
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 10; // Modifies actual array slot
}
System.out.println("arr[0] after fix: " + arr[0]); // 10
// ā
Enhanced for with Set (unordered ā no index guarantee)
Set<Integer> primeSet = new HashSet<>(Set.of(2, 3, 5, 7, 11));
System.out.print("Primes: ");
for (int p : primeSet) {
System.out.print(p + " "); // Order not guaranteed for HashSet
}
System.out.println();
// ā
Enhanced for with Map.entrySet()
Map<String, Integer> scores2 = new LinkedHashMap<>();
scores2.put("Alice", 95);
scores2.put("Bob", 87);
scores2.put("Carol", 92);
for (Map.Entry<String, Integer> entry : scores2.entrySet()) {
System.out.printf("%s: %d%n", entry.getKey(), entry.getValue());
}
}
}For Loop with Arrays ā The Essential Pattern
Arrays and for loops are inseparable in Java. The for loop is the primary tool for array traversal, searching, sorting, filling, copying, and manipulation. Understanding how to use for loops with single-dimensional, multi-dimensional, and jagged arrays is a core Java skill.
import java.util.Arrays;
public class ForLoopArrays {
public static void main(String[] args) {
// ā
Fill array with squares
int[] squares = new int[10];
for (int i = 0; i < squares.length; i++) {
squares[i] = (i + 1) * (i + 1);
}
System.out.println("Squares: " + Arrays.toString(squares));
// [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
// ā
Linear search
int[] data = {34, 7, 23, 32, 5, 62};
int target = 23;
int foundAt = -1;
for (int i = 0; i < data.length; i++) {
if (data[i] == target) {
foundAt = i;
break;
}
}
System.out.println(target + " found at index: " + foundAt); // 2
// ā
Reverse array in-place
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
System.out.println("Reversed: " + Arrays.toString(arr)); // [5, 4, 3, 2, 1]
// ā
Bubble sort using nested for loops
int[] toSort = {64, 34, 25, 12, 22, 11, 90};
int n = toSort.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (toSort[j] > toSort[j + 1]) {
int temp = toSort[j];
toSort[j] = toSort[j + 1];
toSort[j + 1] = temp;
}
}
}
System.out.println("Sorted: " + Arrays.toString(toSort));
// [11, 12, 22, 25, 34, 64, 90]
// ā
2D array traversal
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("Matrix diagonal sum:");
int diagSum = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.printf("%3d", matrix[i][j]);
if (i == j) diagSum += matrix[i][j]; // Main diagonal
}
System.out.println();
}
System.out.println("Diagonal sum: " + diagSum); // 15
// ā
Jagged array (different row lengths)
int[][] jagged = {{1}, {2, 3}, {4, 5, 6}, {7, 8, 9, 10}};
System.out.println("Jagged array:");
for (int i = 0; i < jagged.length; i++) {
for (int j = 0; j < jagged[i].length; j++) { // jagged[i].length varies
System.out.print(jagged[i][j] + " ");
}
System.out.println();
}
// 1
// 2 3
// 4 5 6
// 7 8 9 10
}
}Break and Continue in For Loop
break and continue are loop control statements that alter the normal flow of a for loop. break exits the loop entirely. continue skips the current iteration's remaining body and proceeds to the update step, then condition check. A critical advantage of the for loop: the update expression in the header always executes after continue ā unlike in a while loop where forgetting to update before continue causes an infinite loop.
break immediately exits the for loop ā the update and condition are not executed for that iteration. Execution resumes at the statement after the closing brace of the for loop. Use break for: early exit on target found (linear search), stopping when a condition is met (first invalid element), exiting infinite for(;;) loops, and limiting iterations in retry patterns. Labeled break (break label;) exits a specified outer loop when dealing with nested loops ā used when inner loop needs to break out of multiple levels.
continue skips the remaining body of the current iteration and jumps to the update expression (i++ etc.), then to the condition check. This is a key advantage over while loops ā in a for loop, continue can never accidentally skip the update because the update is in the header, not the body. Use continue for: skipping specific values (null checks, even/odd filtering), ignoring invalid data, processing only elements that meet a condition, and simplifying nested if-else inside loops by using guard-clause style with continue.
Java supports labeled break and continue for nested loops. A label is an identifier followed by a colon placed before a loop: outer: for(...) { inner: for(...) { break outer; } }. break outer exits the outer loop entirely from inside the inner loop. continue outer skips to the outer loop's next iteration. Labels are rarely needed ā most use cases can be solved by extracting to a method and using return. But they are valid Java and occasionally the cleanest solution for nested loop control flow, especially in matrix/grid traversal algorithms.
public class BreakContinueForLoop {
public static void main(String[] args) {
// ā
break ā exit on first match (linear search)
System.out.println("--- break in for loop ---");
int[] arr = {3, 7, 1, 9, 4, 6, 2};
int target = 9;
int foundIndex = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
foundIndex = i;
break; // Stop searching once found
}
}
System.out.println(target + " found at index: " + foundIndex); // 3
// ā
continue ā skip specific values (print odd numbers only)
System.out.println("\n--- continue in for loop ---");
System.out.print("Odd numbers 1-10: ");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // Skip even ā i++ in header ALWAYS runs
System.out.print(i + " "); // 1 3 5 7 9
}
System.out.println();
// ā
continue ā skip null/blank strings
String[] names = {"Alice", null, "Bob", "", "Charlie", null, "David"};
System.out.print("Valid names: ");
for (String name : names) {
if (name == null || name.isBlank()) continue;
System.out.print(name + " ");
}
System.out.println();
// Output: Alice Bob Charlie David
// ā
Labeled break ā exit outer loop from inner
System.out.println("\n--- labeled break ---");
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int searchVal = 5;
int row = -1, col = -1;
outer: // Label for outer loop
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == searchVal) {
row = i;
col = j;
break outer; // Exit BOTH loops
}
}
}
System.out.println(searchVal + " found at [" + row + "][" + col + "]"); // [1][1]
// ā
Labeled continue ā skip outer iteration from inner
System.out.println("\n--- labeled continue ---");
System.out.println("Rows without any zero:");
outerLoop:
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == 0) {
continue outerLoop; // Skip this entire row
}
}
System.out.println(" Row " + i + ": no zeros");
}
// ā
break in infinite for(;;) loop
System.out.println("\n--- break in infinite for ---");
int count = 0;
for (;;) { // Infinite loop
count++;
System.out.print(count + " ");
if (count == 5) break; // Exit when count reaches 5
}
System.out.println("\nStopped at: " + count); // 5
}
}Nested For Loops ā Patterns, Arrays & Algorithms
Nested for loops place one for loop inside another. The inner loop executes completely for every single iteration of the outer loop. Nested loops are essential for 2D array operations, pattern printing, sorting algorithms, and combinatorial problems. The total number of body executions is the product of both loops' iteration counts.
public class NestedForLoops {
public static void main(String[] args) {
// ā
Example 1: Multiplication table grid (1-5 x 1-5)
System.out.println("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();
}
// 1 2 3 4 5
// 2 4 6 8 10
// 3 6 9 12 15 etc.
// ā
Example 2: Right triangle star pattern
System.out.println("\nRight Triangle:");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// *
// * *
// * * *
// * * * *
// * * * * *
// ā
Example 3: Inverted triangle
System.out.println("\nInverted Triangle:");
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// ā
Example 4: Number pattern ā Floyd's triangle
System.out.println("\nFloyd's Triangle:");
int num = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%3d", num++);
}
System.out.println();
}
// 1
// 2 3
// 4 5 6
// 7 8 9 10
// 11 12 13 14 15
// ā
Example 5: Pyramid pattern (centered)
System.out.println("\nPyramid:");
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int s = 1; s <= rows - i; s++) System.out.print(" "); // Spaces
for (int j = 1; j <= 2 * i - 1; j++) System.out.print("*"); // Stars
System.out.println();
}
// *
// ***
// *****
// *******
// *********
// ā
Example 6: Diamond pattern
System.out.println("\nDiamond:");
int n = 5;
// Upper half
for (int i = 1; i <= n; i++) {
for (int s = n; s > i; s--) System.out.print(" ");
for (int j = 1; j <= 2 * i - 1; j++) System.out.print("*");
System.out.println();
}
// Lower half
for (int i = n - 1; i >= 1; i--) {
for (int s = n; s > i; s--) System.out.print(" ");
for (int j = 1; j <= 2 * i - 1; j++) System.out.print("*");
System.out.println();
}
// ā
Example 7: Matrix multiplication (O(n³) ā classic nested loop)
int[][] A = {{1, 2}, {3, 4}};
int[][] B = {{5, 6}, {7, 8}};
int size = 2;
int[][] C = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
for (int k = 0; k < size; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
System.out.println("\nMatrix C[0][0]: " + C[0][0]); // 19
System.out.println("Matrix C[1][1]: " + C[1][1]); // 50
}
}For Loop vs Do-While Loop ā When to Use Which
The for loop and do-while loop are at opposite ends of the loop spectrum. The for loop is entry-controlled with a known count. The do-while is exit-controlled with a guaranteed first execution. Choosing between them correctly signals clear intent in your code.
public class ForVsDoWhile {
public static void main(String[] args) {
// ā
For loop ā best for known count (array traversal)
int[] grades = {85, 92, 78, 96, 88};
int total = 0;
for (int grade : grades) {
total += grade;
}
System.out.println("Average: " + (total / grades.length)); // 87
// for-each is the natural, clearest choice here
// ā
Do-while ā best for 'must run at least once' (menu/validation)
// Simulated: keep prompting until valid grade is entered
int[] simulatedInputs = {-5, 150, 88}; // Invalid, invalid, valid
int idx = 0;
int validGrade;
do {
validGrade = simulatedInputs[idx++];
System.out.println("Entered grade: " + validGrade);
if (validGrade < 0 || validGrade > 100)
System.out.println(" Invalid! Try again.");
} while (validGrade < 0 || validGrade > 100);
System.out.println("Valid grade accepted: " + validGrade); // 88
// ā
For loop for fixed game rounds ā NOT do-while
System.out.println("\nPlaying 3 rounds:");
for (int round = 1; round <= 3; round++) {
int score = (int)(Math.random() * 100);
System.out.println(" Round " + round + " score: " + score);
}
// Known count (3 rounds) = for loop is correct choice
// ā
Do-while for unknown rounds ā play until user stops
String[] choices = {"Y", "Y", "N"}; // Simulated play-again choices
int gameIdx = 0;
int roundNum = 0;
do {
roundNum++;
System.out.println("Playing round " + roundNum + "...");
String playAgain = choices[gameIdx++];
System.out.println("Play again? " + playAgain);
if (playAgain.equalsIgnoreCase("N")) break;
} while (true);
System.out.println("Total rounds played: " + roundNum); // 3
}
}Infinite For Loop ā for(;;)
An infinite for loop is written as for(;;) ā all three header parts are omitted. With no condition, the loop runs forever. It is functionally identical to while(true) and must be exited with break, return, or by throwing an exception. The for(;;) form is a recognized Java idiom, often preferred in systems and server-side code for clarity.
import java.util.*;
public class InfiniteForLoop {
public static void main(String[] args) {
// ā
Pattern 1: for(;;) as event loop (simulated)
System.out.println("--- Event Processing Loop ---");
Queue<String> events = new LinkedList<>(List.of("CONNECT", "REQUEST", "RESPONSE", "SHUTDOWN"));
for (;;) {
if (events.isEmpty()) {
System.out.println("No more events. Exiting.");
break;
}
String event = events.poll();
System.out.println("Processing: " + event);
if ("SHUTDOWN".equals(event)) {
System.out.println("Shutdown received. Stopping loop.");
break;
}
}
// ā
Pattern 2: Retry with max attempts using for(;;)
System.out.println("\n--- Retry Loop ---");
int maxRetries = 4;
int attempt = 0;
for (;;) {
attempt++;
System.out.println("Attempt " + attempt + ": connecting...");
boolean connected = attempt == 3; // Simulated: succeeds on 3rd try
if (connected) {
System.out.println("ā
Connected on attempt " + attempt);
break;
}
if (attempt >= maxRetries) {
System.out.println("ā Failed after " + maxRetries + " attempts.");
break;
}
System.out.println(" Retrying in " + (attempt * 500) + "ms...");
}
// ā
Pattern 3: Number guessing game frame (simulated input)
System.out.println("\n--- Guessing Game ---");
int secret = 42;
int[] guesses = {10, 60, 42}; // Simulated guesses
int gi = 0;
for (;;) {
int guess = guesses[gi++];
System.out.println("Guess: " + guess);
if (guess == secret) {
System.out.println("š Correct in " + gi + " guesses!");
break;
} else if (guess < secret) {
System.out.println(" Too low.");
} else {
System.out.println(" Too high.");
}
}
// ā
for(;;) vs while(true) ā identical bytecode, different style
// Both are accepted Java idioms.
// for(;;) is more common in systems/server code.
// while(true) reads more naturally as 'run forever'.
// Choose based on your team's style guide.
int counter = 0;
for (;;) {
if (++counter >= 3) break;
System.out.println("for(;;) counter: " + counter);
}
}
}Common Mistakes & Pitfalls ā Bugs That Fool Everyone
These are the most common for loop mistakes in Java ā off-by-one errors, semicolon after the header, infinite loops from missing updates, and subtle scoping issues that trip up beginners and occasionally experienced developers too.
// ā MISTAKE 1: Semicolon after for header ā empty body!
// for (int i = 0; i < 5; i++); // ā This semicolon creates an empty body!
// {
// System.out.println(i); // This runs ONCE after the loop ā outside it
// }
// The semicolon terminates the for statement; the block {} is a separate statement.
// ā
Fix: no semicolon after the for header
for (int i = 0; i < 5; i++) {
System.out.println(i); // ā
Correct
}
// ā MISTAKE 2: Off-by-one ā using < vs <=
int[] arr = {10, 20, 30, 40, 50};
// for (int i = 0; i <= arr.length; i++) { // ā ArrayIndexOutOfBoundsException at i=5
// System.out.println(arr[i]);
// }
// ā
Fix: use < arr.length (not <=)
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " "); // ā
}
System.out.println();
// ā MISTAKE 3: Modifying loop variable inside body (unexpected behavior)
// for (int i = 0; i < 5; i++) {
// System.out.println(i);
// i++; // ā i incremented TWICE per iteration ā prints only 0, 2, 4
// }
// ā
Fix: update ONLY in the header unless intentional
for (int i = 0; i < 5; i++) {
System.out.print(i + " "); // 0 1 2 3 4 ā correct
}
System.out.println();
// ā MISTAKE 4: Variable scope ā accessing loop variable outside loop
for (int i = 0; i < 3; i++) { }
// System.out.println(i); // ā COMPILE ERROR: i not accessible here
// ā
Fix: declare before loop if needed outside
int j;
for (j = 0; j < 3; j++) { }
System.out.println("j after loop: " + j); // ā
j = 3
// ā MISTAKE 5: Float/double loop variable ā precision errors
// for (double d = 0.0; d != 1.0; d += 0.1) { // ā May NEVER equal exactly 1.0!
// System.out.println(d); // Runs forever or terminates unpredictably
// }
// ā
Fix: use integer counter, or use < with tolerance
for (int i = 0; i <= 10; i++) {
double d = i * 0.1;
System.out.printf("%.1f ", d); // 0.0 0.1 0.2 ... 1.0
}
System.out.println();
// ā MISTAKE 6: ConcurrentModificationException in enhanced for + List modification
java.util.List<String> list = new java.util.ArrayList<>(java.util.List.of("A","B","C"));
// for (String s : list) {
// if (s.equals("B")) list.remove(s); // ā ConcurrentModificationException!
// }
// ā
Fix: use removeIf (Java 8+) or Iterator
list.removeIf(s -> s.equals("B")); // ā
Safe removal
System.out.println("List after remove: " + list); // [A, C]
// ā MISTAKE 7: Infinite loop from wrong condition direction
// for (int i = 0; i >= 0; i++) { // ā i grows forever ā infinite loop
// System.out.println(i);
// }
// ā
Fix: ensure condition becomes false ā use i-- for countdown
for (int i = 5; i > 0; i--) {
System.out.print(i + " "); // 5 4 3 2 1
}
System.out.println();Bad Practices & Anti-Patterns ā What Senior Developers Reject
These anti-patterns represent common misuses of for loops in professional Java code. Each one either causes bugs, reduces readability, or makes code harder to maintain and test.
Java allows a for loop with a single statement and no braces: for(int i=0; i<5; i++) System.out.println(i); ā but this is dangerous and universally rejected in professional code. Adding a second statement below it while thinking it is inside the loop creates a silent logic bug (it runs only once, after the loop ends). Always use curly braces for all for loop bodies. Every major Java style guide (Google, Oracle) mandates braces. There are no exceptions to this rule in production code.
Writing for(int i=0; i<7; i++) or for(int i=0; i<students.length; i++) with the literal 7 as a magic number makes intent unclear and changes fragile. Define named constants: private static final int DAYS_IN_WEEK = 7; then use for(int i=0; i<DAYS_IN_WEEK; i++). For array bounds, always use arr.length ā never hardcode the size. SonarQube and other static analysis tools flag magic numbers in loop conditions as code quality violations.
Writing for(int i=0; i<list.size(); i++) { process(list.get(i)); } when you do not need the index is unnecessarily verbose. The enhanced for loop for(String s : list) { process(s); } is shorter, more readable, and communicates 'process every element' without the noise of index management. Reserve the traditional indexed for loop for cases that genuinely require the index. Using it everywhere 'just in case' you need the index is an anti-pattern that clutters code.
Writing for(int i=0; i<list.size(); i++) calls list.size() on every iteration. For ArrayList this is O(1) and harmless, but for custom collections or LinkedList variants it could be O(n), making the loop O(n²). Best practice: cache the size before the loop: int size = list.size(); for(int i=0; i<size; i++). For arrays, arr.length is a field access (O(1)) so caching is optional ā but for collections, always cache the size for clarity and safety.
Three or more levels of nested for loops create code that is nearly impossible to read, debug, and test. It is a strong signal to refactor: extract inner loops into separate methods with descriptive names (e.g. processRow, findColumn), replace O(n²) search loops with HashMap lookups, use Java Streams for filtering and transformation, or break the problem into smaller composable functions. Deep nesting also indicates O(n³) or worse complexity ā always evaluate algorithmic alternatives before accepting cubic-time nested loops.
Adding or removing elements from a List, Set, or Map while iterating it with an enhanced for loop causes ConcurrentModificationException at runtime. This is a common but easily avoided mistake. Never modify the collection being iterated in a for-each. Instead: use list.removeIf(predicate) for removals (Java 8+), collect items to a separate list and process after the loop, use Iterator explicitly with iterator.remove() for safe removal during iteration, or use a traditional indexed for loop when mutation is required.
Real-World Production Code Examples ā For Loop in Context
The following examples show idiomatic, production-grade Java for loop usage ā patterns seen in real Spring Boot services, data processing pipelines, and enterprise Java codebases.
package com.techsustainify.reports;
import java.util.*;
public class ReportGenerator {
record Student(String name, int[] marks) {}
// ā
Generate report for all students
public void generateClassReport(List<Student> students) {
if (students == null || students.isEmpty()) {
System.out.println("No students to report.");
return;
}
System.out.println("āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā");
System.out.println("ā CLASS PERFORMANCE REPORT ā");
System.out.println("āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā");
int classTotal = 0;
int highestAverage = 0;
String topper = "";
// ā
For-each ā no index needed for student processing
for (Student student : students) {
int sum = 0;
int highest = 0;
int lowest = Integer.MAX_VALUE;
// ā
Traditional for ā need index for subject numbering
for (int i = 0; i < student.marks().length; i++) {
int mark = student.marks()[i];
sum += mark;
if (mark > highest) highest = mark;
if (mark < lowest) lowest = mark;
System.out.printf(" Subject %d: %d%n", i + 1, mark);
}
int avg = sum / student.marks().length;
classTotal += avg;
if (avg > highestAverage) {
highestAverage = avg;
topper = student.name();
}
String grade = avg >= 90 ? "A+" : avg >= 80 ? "A" : avg >= 70 ? "B" : avg >= 60 ? "C" : "F";
System.out.printf("%-15s | Avg: %3d | High: %3d | Low: %3d | Grade: %s%n",
student.name(), avg, highest, lowest, grade);
}
System.out.println("Class Average: " + (classTotal / students.size()));
System.out.println("Top Performer: " + topper + " (" + highestAverage + ")");
}
public static void main(String[] args) {
List<Student> students = List.of(
new Student("Alice", new int[]{92, 88, 95, 91, 89}),
new Student("Bob", new int[]{75, 82, 70, 78, 85}),
new Student("Charlie", new int[]{60, 65, 58, 72, 68})
);
new ReportGenerator().generateClassReport(students);
}
}package com.techsustainify.data;
import java.util.*;
public class DataProcessor {
private static final int MAX_AGE = 120;
private static final int MIN_AGE = 0;
private static final int MAX_SALARY = 10_000_000;
record Employee(String name, int age, double salary) {}
// ā
Validate and transform a batch of employee records
public List<Employee> processEmployeeData(List<String[]> rawData) {
List<Employee> validEmployees = new ArrayList<>();
List<String> errors = new ArrayList<>();
// ā
Traditional for with index ā need row number for error reporting
for (int i = 0; i < rawData.size(); i++) {
String[] row = rawData.get(i);
int rowNum = i + 1; // 1-based for human-readable error messages
if (row.length != 3) {
errors.add("Row " + rowNum + ": Expected 3 columns, got " + row.length);
continue;
}
String name = row[0].strip();
if (name.isBlank()) {
errors.add("Row " + rowNum + ": Name cannot be blank");
continue;
}
int age;
try {
age = Integer.parseInt(row[1].strip());
} catch (NumberFormatException e) {
errors.add("Row " + rowNum + ": Invalid age '" + row[1] + "'");
continue;
}
if (age < MIN_AGE || age > MAX_AGE) {
errors.add("Row " + rowNum + ": Age " + age + " out of range [" + MIN_AGE + "-" + MAX_AGE + "]");
continue;
}
double salary;
try {
salary = Double.parseDouble(row[2].strip());
} catch (NumberFormatException e) {
errors.add("Row " + rowNum + ": Invalid salary '" + row[2] + "'");
continue;
}
if (salary < 0 || salary > MAX_SALARY) {
errors.add("Row " + rowNum + ": Salary " + salary + " out of range");
continue;
}
validEmployees.add(new Employee(name, age, salary));
}
// ā
For-each for reporting ā no index needed
if (!errors.isEmpty()) {
System.out.println("\nā ļø Validation Errors:");
for (String error : errors) {
System.out.println(" " + error);
}
}
System.out.println("\nā
Valid records: " + validEmployees.size() + "/" + rawData.size());
return validEmployees;
}
public static void main(String[] args) {
List<String[]> data = List.of(
new String[]{"Alice", "30", "75000"},
new String[]{"Bob", "200", "50000"}, // Invalid age
new String[]{"", "25", "60000"}, // Blank name
new String[]{"Charlie", "abc", "80000"}, // Invalid age format
new String[]{"Diana", "28", "90000"}
);
new DataProcessor().processEmployeeData(data);
}
}For Loop Flow Diagram ā Visualizing Execution
This flowchart shows the execution flow of the for loop ā highlighting how initialization runs exactly once, the condition is checked before every iteration including the first, and the update runs after every body execution but before the next condition check.
Code Execution Flow ā from source to output
Java For Loop Interview Questions ā Beginner to Advanced
For loop questions test your understanding of entry-controlled loops, the three-part header, variable scope, enhanced for loop limitations, and the behavior of break and continue. These appear frequently in Java interviews at all levels.
Practice Questions ā Test Your For Loop Knowledge
Challenge yourself with these practice questions. Attempt each independently before reading the answer ā writing and tracing code by hand significantly improves retention and interview readiness.
1. What is the output? for (int i = 1; i <= 5; i++) { if (i % 2 == 0) continue; System.out.print(i + " "); }
Easy2. What is printed after this code runs? int sum = 0; for (int i = 1; i <= 10; i++) { if (i % 3 == 0) continue; sum += i; } System.out.println(sum);
Easy3. Write a for loop program to check whether a given number is a perfect number (sum of its proper divisors equals the number itself). Example: 28 = 1+2+4+7+14.
Medium4. Trace the output of this code: int result = 0; for (int i = 1; i <= 5; i++) { result += i * i; if (result > 20) break; } System.out.println(result);
Medium5. Using nested for loops, print the following pattern: 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1
Medium6. What is the output? Why? int x = 0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i == j) break; x++; } } System.out.println(x);
Hard7. Write a program using a for loop to find all Armstrong numbers between 1 and 1000. (An Armstrong number equals the sum of its digits each raised to the power of the number of digits ā e.g., 153 = 1³+5³+3³.)
Hard8. What is the difference in variable accessibility after these two loops? // Loop A for (int i = 0; i < 3; i++) { } // Loop B int j = 0; for (; j < 3; j++) { }
EasyConclusion ā For Loop: The Workhorse of Java Iteration
The for loop is Java's most versatile and widely used loop. Its three-part header ā initialization, condition, update ā keeps all iteration control in one compact, readable line. It is the natural choice whenever you know how many times to iterate, need an index, or are traversing an array or collection by position.
Mastering the for loop means understanding not just its syntax ā the two mandatory semicolons, the scoping of the loop variable, the always-safe continue behavior ā but also its variants: the enhanced for loop for clean collection iteration, multiple variable headers for two-pointer patterns, labeled break/continue for nested loop control, and for(;;) for intentional infinite loops. Choosing the right loop type ā for, while, or do-while ā and using the right variant ā traditional or enhanced ā is the mark of an experienced Java developer.
Your next step: Java While Loop ā the other entry-controlled loop, best for unknown iteration counts, event-driven conditions, and scenarios where the for loop's structure would feel forced or unnatural. ā