Java for Loop Explained — Syntax, Examples and Common Mistakes
Almost every real program needs to repeat something. A banking app applies interest to thousands of accounts. A game redraws the screen 60 times per second. A search engine scores millions of web pages. Without a way to repeat code automatically, you'd have to copy and paste the same lines thousands of times — and then the first bug would require thousands of fixes. That's not programming, that's punishment.
The for loop solves this elegantly. It lets you write an action once and tell Java exactly how many times to run it. It also keeps a counter variable automatically, so you always know which repetition you're on. This makes it perfect for any situation where you know in advance how many times something needs to happen — like processing every item in a list, or printing a times table.
By the end of this article you'll understand every part of a for loop's syntax, be able to write one from scratch without looking anything up, know how to loop through arrays, nest one loop inside another, and spot the two mistakes that trip up nearly every beginner. You'll also walk away with the answers to the for loop questions that show up in junior Java interviews.
Anatomy of a Java for Loop — What Each Part Actually Does
A for loop has three parts crammed into one line, separated by semicolons. Each part has a specific job, and understanding each job separately makes the whole thing click.
The first part is the initializer. It runs exactly once — right before the loop starts. You use it to create and set your counter variable. Think of it as setting the odometer to zero before a road trip.
The second part is the condition. Java checks this before every single repetition. If it's true, the loop body runs. If it's false, the loop stops immediately and Java moves on. This is the gatekeeper.
The third part is the update. It runs after every repetition of the loop body — right before the condition is checked again. You use it to change your counter so the loop eventually ends.
That order matters: initializer → check condition → run body → update → check condition again → and so on. Miss any of those three parts and the loop either never starts, or never stops. Let's see all three in action with a concrete example.
public class BirthdayInvitations { public static void main(String[] args) { // We need to write 5 birthday invitations. // The for loop handles the counting for us. // // Part 1 — int invitationNumber = 1 // Creates a counter and starts it at 1. // Runs ONCE before the loop begins. // // Part 2 — invitationNumber <= 5 // The gatekeeper. Checked before every repetition. // When invitationNumber hits 6, this is false and the loop stops. // // Part 3 — invitationNumber++ // Adds 1 to our counter after each repetition. // invitationNumber++ is shorthand for invitationNumber = invitationNumber + 1 for (int invitationNumber = 1; invitationNumber <= 5; invitationNumber++) { System.out.println("Writing invitation #" + invitationNumber); } // This line runs AFTER the loop finishes — the loop does not affect it. System.out.println("All invitations written!"); } }
Writing invitation #2
Writing invitation #3
Writing invitation #4
Writing invitation #5
All invitations written!
Looping Through an Array — The Most Common Real-World Use Case
The single most common use of a for loop in Java is walking through every element of an array. An array is just a numbered list of values — like a row of lockers, each with a number starting from 0.
That 'starting from 0' detail is critical. In Java, arrays are zero-indexed. The first element is at position 0, not 1. A 5-element array has positions 0, 1, 2, 3, 4. The last valid position is always the array's length minus one. This is exactly why most loops that iterate over arrays start their counter at 0 and use the condition i < array.length rather than i <= array.length — using <= would send your counter one slot past the end of the array and cause a crash.
The loop counter doubles as the index, which is the clever part. On the first pass i is 0 so you read element 0. On the second pass i is 1 so you read element 1. The loop and the array stay in perfect sync automatically.
Let's build something real — calculating the total score from a student's test results.
public class StudentScoreCalculator { public static void main(String[] args) { // An array of five test scores for a student. // Array positions: [0]=85 [1]=92 [2]=78 [3]=95 [4]=88 int[] testScores = {85, 92, 78, 95, 88}; int totalScore = 0; // We'll add each score into this. // testScores.length is 5, so the loop runs for i = 0, 1, 2, 3, 4 // Notice: i < testScores.length (NOT <=) — this is intentional. // If we used <= 5, we'd try to read testScores[5] which doesn't exist. for (int i = 0; i < testScores.length; i++) { System.out.println("Score " + (i + 1) + ": " + testScores[i]); totalScore = totalScore + testScores[i]; // accumulate the running total } // Calculate the average — we know there are exactly 5 scores double averageScore = (double) totalScore / testScores.length; System.out.println("----------------------------"); System.out.println("Total Score : " + totalScore); System.out.printf("Average Score: %.1f%n", averageScore); } }
Score 2: 92
Score 3: 78
Score 4: 95
Score 5: 88
----------------------------
Total Score : 438
Average Score: 87.6
Nested for Loops — Loops Inside Loops (And When You Actually Need Them)
Sometimes one dimension of repetition isn't enough. Imagine printing a multiplication table — you need every number from 1 to 10 multiplied by every other number from 1 to 10. That's a grid. Grids have rows and columns, and that's exactly where nested loops shine.
A nested loop is simply a loop inside another loop. The outer loop controls rows. The inner loop controls columns. For every single iteration of the outer loop, the inner loop runs all the way through its full cycle. So if the outer loop runs 3 times and the inner loop runs 4 times, the loop body executes 3 × 4 = 12 times total.
The variable names matter here. Use row and col, or i and j — but never use i for both loops. Each loop needs its own independent counter variable or they'll overwrite each other and produce nonsense.
Nested loops are also used in real-world code to compare every element in a list against every other element, to process 2D grids in games, and to validate matrix data in data science applications.
public class MultiplicationTable { public static void main(String[] args) { int tableSize = 5; // We'll print a 5x5 multiplication table System.out.println("--- 5x5 Multiplication Table ---"); // OUTER LOOP: controls which row we're on (1 through 5) for (int row = 1; row <= tableSize; row++) { // INNER LOOP: controls which column we're on (1 through 5) // For every single value of 'row', this entire inner loop // runs from col=1 all the way to col=5. for (int col = 1; col <= tableSize; col++) { int product = row * col; // %4d means: print an integer, padded to 4 characters wide. // This keeps the columns aligned neatly. System.out.printf("%4d", product); } // After the inner loop finishes one full row, move to the next line. System.out.println(); } } }
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
Controlling Loop Flow with break and continue
Sometimes you need to exit a loop early, or skip one specific iteration without stopping the whole loop. Java gives you two keywords for this: break and continue.
break is the emergency exit. The moment Java hits break, it leaves the loop entirely — no more iterations, no going back. This is useful when you're searching for something and you've found it. There's no point checking the rest of the list once you've already got your answer.
continue is more subtle. It doesn't stop the loop — it just skips the rest of the current iteration and jumps straight to the update step, then rechecks the condition. Think of it as 'never mind this one, carry on to the next.' This is handy when you want to process most items but ignore a specific type.
Both keywords work in nested loops too, but they only affect the loop they're directly inside. To break out of an outer loop from inside an inner loop, Java supports labeled breaks — but that's an advanced topic for another day.
public class SecurityScanner { public static void main(String[] args) { // Simulating a list of usernames being scanned. // We want to: // 1. Skip any username that is blank (continue) // 2. Stop scanning immediately if we find a banned user (break) String[] usernames = {"alice", "bob", "", "charlie", "BANNED_USER", "diana"}; System.out.println("Starting security scan..."); for (int i = 0; i < usernames.length; i++) { // If the username is blank, skip it — nothing to check. // 'continue' jumps straight to i++ then rechecks the condition. if (usernames[i].isEmpty()) { System.out.println("Slot " + i + ": empty — skipping."); continue; } // If we find the banned user, raise the alarm and stop scanning. // 'break' exits the for loop immediately. if (usernames[i].equals("BANNED_USER")) { System.out.println("ALERT: Banned user detected at slot " + i + "! Halting scan."); break; } // This line only runs if neither condition above triggered. System.out.println("Slot " + i + ": '" + usernames[i] + "' cleared."); } System.out.println("Scan complete."); } }
Slot 0: 'alice' cleared.
Slot 1: 'bob' cleared.
Slot 2: empty — skipping.
Slot 3: 'charlie' cleared.
ALERT: Banned user detected at slot 4! Halting scan.
Scan complete.
| Aspect | for Loop | while Loop |
|---|---|---|
| Best used when | You know the number of iterations in advance | You don't know how many iterations you'll need |
| Counter variable | Declared and managed inside the loop header | Declared outside the loop, updated manually inside |
| Readability | All loop logic visible in one line | Loop logic is spread across multiple lines |
| Risk of infinite loop | Lower — update step is part of the syntax | Higher — easy to forget updating the counter |
| Iterating an array | Natural fit — use array.length as the bound | Works but requires more boilerplate code |
| Typical example | Print numbers 1 to 100 | Keep reading input until the user types 'quit' |
🎯 Key Takeaways
- The for loop header has three parts separated by semicolons: initializer (runs once), condition (checked before every iteration), and update (runs after every iteration). All three work together — remove any one and the loop breaks.
- Arrays in Java are zero-indexed, so always start your loop counter at 0 and use
i < array.lengthas your condition — not<=. Off-by-one errors here cause ArrayIndexOutOfBoundsException at runtime. breakexits the entire loop immediately.continueonly skips the rest of the current iteration and moves to the next one. Confusing them produces silent logic bugs, not compile errors.- Nested loops multiply — an outer loop running N times and an inner loop running M times means the body executes N × M times. This scales badly with large data, so always ask whether you genuinely need two loops before nesting them.
⚠ Common Mistakes to Avoid
- ✕Mistake 1: Using
i <= array.lengthinstead ofi < array.length— Symptom is a runtime crash:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5. Fix: arrays are zero-indexed, so the last valid index is alwayslength - 1. Usei < array.lengthas your condition, which stops the counter one step before it goes out of bounds. - ✕Mistake 2: Accidentally creating an infinite loop by using the wrong update operator — For example, writing
i--when you meanti++in a loop that counts upward. The counter moves away from the stopping condition, so the condition is always true and the loop never ends. Your program freezes. Fix: always double-check that your update operator moves the counter toward the condition that will make it false. If you're counting up toward a maximum, usei++. If you're counting down toward a minimum, usei--. - ✕Mistake 3: Putting a semicolon immediately after the for loop header — Writing
for (int i = 0; i < 5; i++);creates an empty loop body. The semicolon acts as a blank statement, so the loop runs 5 times doing nothing, then the block beneath it runs exactly once. This is a classic silent bug — no error, wrong output. Fix: never put a semicolon directly after the closing parenthesis of a for loop. The opening curly brace{should come next.
Interview Questions on This Topic
- QWhat are the three parts of a Java for loop header, and in what order does Java execute them? Can any of the three parts be left empty, and if so what happens?
- QWhat is the difference between `break` and `continue` in a for loop? Write a short example that uses both in the same loop to demonstrate you understand the distinction.
- QIf you have a for loop with `i = 0`, condition `i < 10`, and update `i++`, how many times does the loop body execute? How many times is the condition checked? (Trick: the condition is checked 11 times — once for each of the 10 successful iterations, plus the final check when `i` equals 10 and the loop exits.)
Frequently Asked Questions
What is a for loop in Java and when should I use it?
A for loop is a control flow statement that repeats a block of code a specific number of times. Use it whenever you know in advance how many iterations you need — like processing every element in an array, printing a times table, or repeating an action a fixed number of times. When you don't know the number of iterations upfront, a while loop is usually a better fit.
Why does my Java for loop skip the last element of the array?
This usually means your condition is i < array.length - 1 instead of i < array.length. The expression array.length - 1 stops one element too early. Use i < array.length and your loop will correctly visit every element from index 0 to index length - 1.
What happens if I leave the update part of a for loop empty?
Java allows you to omit any of the three parts of a for loop header. If you leave the update empty — like for (int i = 0; i < 10;) — the counter never changes, so the condition stays true forever and you get an infinite loop. Only leave the update empty if you're manually updating the counter somewhere inside the loop body itself.
Written and reviewed by senior developers with real-world experience across enterprise, startup and open-source projects. Every article on TheCodeForge is written to be clear, accurate and genuinely useful — not just SEO filler.