๐Ÿงฐ Java Basics to Intermediate
Estimated reading: 3 minutes 286 views

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 for loop works
  • When to use for, while, or do...while
  • Real-world examples with arrays and collections
  • Loop control using break and continue

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 1
  • i <= 5 โ†’ condition
  • i++ โ†’ increments by 1 each time

Reverse Looping Example

for (int i = 5; i >= 1; i--) {
    System.out.println("Countdown: " + i);
}

Explanation:

  • Decreases i from 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 0 to nums.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:

  • continue skips the current iteration
  • break exits the loop early

For Loop vs While Loop โ€“ Quick Comparison

Featurefor Loopwhile Loop
Known iteration Ideal Not ideal
InitializationInside loop headerOutside loop
Use caseCounted repetitionConditional repetition
Enhanced version for-each available No direct equivalent

Best Practices for Java For Loop

Tips:

  • Use for when number of iterations is known
  • Prefer enhanced for for 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 ArrayIndexOutOfBounds

Summary

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 break and continue for finer control
  • Use enhanced for when 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 :
Share

Java For Loop

Or Copy Link

CONTENTS
Scroll to Top