Java For Loop Explained โ Syntax, For-Each, Examples & Best Practices
Introduction โ Repetition Made Easy
Suppose you want to print numbers 1 through 10 โ doing this manually is inefficient and error-prone. Thatโs where the Java for loop helps.
Itโs one of the most powerful tools for controlled iteration in Java.
In this article, you’ll learn:
- How the basic and enhanced
forloop works - When to use
for,while, ordo...while - Real-world examples with arrays and collections
- Loop control using
breakandcontinue
What is a for Loop in Java?
A for loop lets you execute a block of code a fixed number of times, using a loop counter.
Basic Syntax of Java For Loop
for (initialization; condition; update) {
// code block to be executed
}
Explanation:
- Initialization: Start a counter (e.g.,
int i = 0) - Condition: Runs while
true - Update: Executes after each loop (e.g.,
i++)
Example: Print Numbers 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println("i = " + i);
}
Explanation:
i = 1โ loop starts at 1i <= 5โ conditioni++โ increments by 1 each time
Reverse Looping Example
for (int i = 5; i >= 1; i--) {
System.out.println("Countdown: " + i);
}
Explanation:
- Decreases
ifrom 5 to 1 - Useful for reverse iterations or countdowns
Enhanced For Loop (for-each)
Introduced in Java 5, enhanced for loop is used to iterate through arrays or collections.
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
Explanation:
String fruitโ local variable: fruitsโ the array being looped- Cleaner and safer for read-only traversal
You cannot modify array elements directly in an enhanced for loop.
For Loop with Arrays
int[] nums = {10, 20, 30};
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
Explanation:
- Loops from index
0tonums.length - 1 - Accesses and prints each array element
Using break and continue in For Loops
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // skip when i is 3
if (i == 5) break; // stop when i is 5
System.out.println(i);
}
Output: 1, 2, 4
Explanation:
continueskips the current iterationbreakexits the loop early
For Loop vs While Loop โ Quick Comparison
| Feature | for Loop | while Loop |
|---|---|---|
| Known iteration | Ideal | Not ideal |
| Initialization | Inside loop header | Outside loop |
| Use case | Counted repetition | Conditional repetition |
| Enhanced version | for-each available | No direct equivalent |
Best Practices for Java For Loop
Tips:
- Use
forwhen number of iterations is known - Prefer enhanced
forfor readability when not modifying array - Donโt forget
i++โ or youโll end up in an infinite loop!
Avoid off-by-one errors:
for (int i = 0; i <= arr.length; i++) // causes ArrayIndexOutOfBoundsSummary
Java for loops are ideal for repeated actions with a known number of steps.
Whether you’re working with indexes, arrays, or collections, for provides clean and effective control.
Key Takeaways:
- Master both basic and enhanced for loops
- Apply
breakandcontinuefor finer control - Use enhanced
forwhen reading from arrays or lists
FAQs โ Java For Loop
What is the difference between for and enhanced for loop?
The enhanced for (for-each) loop simplifies iterating over arrays and collections, but itโs not suitable for modifying elements.
Can I use break and continue in a for loop?
Yes! break exits the loop, and continue skips to the next iteration.
When should I use a for loop over a while loop?
Use a for loop when you know how many times you need to iterate.
Can we use multiple variables in a for loop?
Yes, you can initialize and update multiple variables:
for (int i = 0, j = 10; i < j; i++, j--) { }
Does Java have a foreach loop?
Yes! The enhanced for loop is Javaโs version of foreach.
Share Now :
