For Loop in Java: Syntax, Examples

A for loop in Java is an entry-controlled flow statement that allows you to execute a block of code multiple times based on a condition. You should use a for loop when you know exactly how many iterations you need to perform. For example, if you want to print numbers from 1 to 10, the for loop is the most efficient tool to do so.

The for loop in Java is one of the most powerful and frequently used constructs for automating repetitive tasks. Whether you’re iterating through arrays, processing collections, or simply printing numbers, the for loop is your go-to control structure for efficient looping.

For loop in Java with syntax, basic to advanced examples.

Syntax of For Loop in Java

The basic syntax of for loop in Java is as:

for (initialization; condition; update) {
    // body of the loop
}

Let’s understand each part in detail.

1. Initialization

Initialization declares and initializes the loop control variable. It executes only once, at the beginning of the loop. For example:

int i = 1;

This part sets up the starting point of the loop.

2. Condition

This is a Boolean expression that’s evaluated before each iteration.
If the condition evaluates to true, the loop body executes. If it’s false, the loop terminates. An example of condition (boolean expression) is given below:

i <= 5;

In the above example, if i becomes greater than 5, the loop stops executing.

3. Update (Increment or Decrement)

This statement executes after each iteration of the loop body. It’s typically used to increment (i++) or decrement (i–) the loop control variable. For example:

i++;

This statement increases the value of i by 1 after every loop iteration.

4. Body

The block of code enclosed in curly braces {} that performs the desired repetitive task.

Putting It All Together

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

Step-by-Step Explanation

Let’s trace how this for loop executes:

StepStatementExplanation
1️⃣int i = 1;Initialization – runs only once.
2️⃣i <= 5;Condition check. If true, execute the loop body.
3️⃣System.out.println(i);Prints the current value of i.
4️⃣i++;Increment i by 1.
5️⃣Repeat steps 2–4Until i <= 5 becomes false.
6️⃣Exit loopWhen condition becomes false (i = 6).

Output:

1
2
3
4
5

How For Loop Works Internally in Java?

Here’s how the for loop works logically:

  1. Initialization
  2. Condition check
  3. Execute loop body
  4. Update variable
  5. Repeat until condition is false

Once the condition becomes false, control exits the loop.

Let’s take the same example program and see what happens behind it.

public class ForLoopExample {
  public static void main(String[] args) {
    for (int i = 1; i <= 3; i++) {
        System.out.println("Value of i: " + i);
    }
  }
}

Iteration Process:

Iteration 1:

  • The initialization step (i = 1) executes.
  • The condition (1 <= 3) is evaluated.
  • If the condition is true, the code inside the loop body is executed and displays the value of i equal to 1.
  • The update statement (i++) is executed. Now the value of i is equal to 2.
  • If the condition is false, the loop terminates, and the program continues with the next statement after the loop.

Iteration 2:

  • The value of i is equal to 2.
  • The test condition 2 <= 3 is evaluated.
  • Since the condition is true, the code inside the loop body is executed and displays the value of i is equal to 2.
  • The update statement (i++) is executed and increments the value of i to 3.

Iteration 3:

  • Now the value of i is equal to 3.
  • The test condition 3 <= 3 is evaluated.
  • Since the condition is true, the code inside the loop body is executed and displays the value of i is equal to 3.
  • The update statement (i++) is executed and increments the value of i to 4.

Iteration 4:

  • i = 4
  • Condition: 4 <= 3 → false
  • Loop terminates.

Final Output:

Value of i: 1
Value of i: 2
Value of i: 3

Key Points to Remember

  • The initialization, condition, and update parts (increment or decrement) are optional, but the semicolons (;) are mandatory.
  • You can have multiple variables in initialization and update parts, separated by commas.
  • A for loop is best when the number of iterations is known in advance.

Advanced Examples of For Loop in Java

Let’s take some advanced example programs based on the for loop in Java. You should must practice these programs.

Example 1: Sum of First N Natural Numbers

public class SumExample {
  public static void main(String[] args) {
     int sum = 0;
     for (int i = 1; i <= 10; i++) {
         sum += i;
     }
     System.out.println("Sum = " + sum);
  }
}

Output:

Sum = 55

Let’s break down the program step by step to clearly understand how it works and how the output is produced.

1. int sum = 0;

  • This line initializes a variable sum with value 0.
  • It will be used to store the cumulative sum of numbers from 1 to 10.

2. for (int i = 1; i <= 10; i++)

  • This is a for loop that controls how many times the code block will run.
  • Initialization: int i = 1 → loop starts with i = 1.
  • Condition: i <= 10 → loop continues until i becomes greater than 10.
  • Update: i++ → after each iteration, i increases by 1.

3. sum += i;

  • This is a shorthand for sum = sum + i;.
  • On each iteration, the value of i is added to the existing value of sum.

Iteration Process (Step-by-Step):

IterationValue of iCalculationNew Value of sum
110 + 11
221 + 23
333 + 36
446 + 410
5510 + 515
6615 + 621
7721 + 728
8828 + 836
9936 + 945
101045 + 1055

4. When i becomes 11,

  • The condition i <= 10 becomes false, so the loop stops executing.

5. System.out.println("Sum = " + sum);

  • This prints the final value of sum on the console.

Thus, this program adds all the numbers from 1 to 10, stores the total in sum, and finally prints the result. So, the output is 55, because 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.

Example 2: Reverse a String Using For Loop

public class ReverseString {
   public static void main(String[] args) {
     String str = "Java";
     String rev = "";

     for (int i = str.length() - 1; i >= 0; i--) {
         rev += str.charAt(i);
     }
     System.out.println("Reversed String: " + rev);
  }
}

Output:

Reversed String: avaJ

Example 3: Printing a Pyramid Pattern

public class PatternExample {
  public static void main(String[] args) {
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= i; j++) {
             System.out.print("* ");
        }
        System.out.println();
    }
  }
}

Output:

* 
* * 
* * * 
* * * * 
* * * * * 

For Loop with Multiple Variables

You can initialize and update multiple variables of the same type in the loop header. For example:

for (int i = 0, j = 10; i < j; i++, j--) {
    System.out.println("i = " + i + ", j = " + j);
}

Output:

i = 0, j = 10
i = 1, j = 9
i = 2, j = 8
...
i = 4, j = 6

Common Mistakes with For Loop

In this section, we have explained some common mistakes that beginners often do while applying for loop in Java program.

MistakeDescriptionExample
1. Missing UpdateCauses infinite loopfor(int i=0; i<5;)
2. Wrong ConditionSkips loop entirelyfor(int i=10; i<5; i++)
3. Modifying Variable Inside LoopCauses unexpected outputChanging i manually in loop body.
4. Using Wrong Data TypeCompile-time errorfor(float i=0; i<5; i++) works, but not recommended.

When to Use For Loop in Java?

You can following scenarios where you can use for loop in Java. They are:

  • When you know the exact number of iterations.
  • You can use for loop for iterating arrays or collections.
  • If you are performing index-based operations, use for loop.
  • Use for loop for pattern generation or nested logic.

FAQs on For Loop in Java

Q1: Can we use multiple variables in a for loop?

Answer: Yes

for (int i = 0, j = 10; i < j; i++, j--) {
    System.out.println(i + " " + j);
}

Q2: Can the for loop run without initialization or update?

Answer: Yes. All three parts of the for loop are optional.

int i = 1;
for(; i <= 5;) {
    System.out.println(i);
    i++;
}

Q3: Is the for-each loop faster than the normal for loop?

Answer: It depends on the requirement. If you are working on arrays, both are the same. But if you are working on collections, the enhanced for loop is more readable and less error-prone.

Q4: Can we use break and continue inside a for loop?

Answer: Yes

for (int i = 1; i <= 10; i++) {
    if (i == 5) break;  // exits loop
    if (i == 3) continue;  // skips iteration
    System.out.println(i);
}

Q5. What happens if you omit all three statements in a for loop?

Answer: It becomes an infinite loop.

Q6. What is the difference between a for loop and a while loop?

Answer: A for loop is best for use when the number of iterations is known beforehand. A while loop is more suitable when the number of iterations depends on a dynamic condition that is evaluated inside the loop body.

Q7. Can a for loop be empty?

Answer: Yes, the body of a for loop can be an empty statement (just a semicolon ;). This is sometimes used for creating time delays. However, it’s not a recommended practice.

for (int i = 0; i < 1000000; i++); // Empty body

Q8. What is an infinite loop and how can I stop one?

Answer: An infinite loop runs forever because its termination condition is never met. To stop one in your IDE, you can usually use a keyboard shortcut (Ctrl + C in the terminal). In your code, ensure your condition will eventually become false or use a break statement with a specific condition.

Conclusion

The for loop in Java is a powerful construct that provides you to handle the repeating task multiple times. From simple counting to complex nested logic, it’s a fundamental construct every Java programmer must make command.

By understanding its basic syntax, execution flow, and various advanced techniques, you can write cleaner, more efficient, and more powerful Java code. So, you must practice all the above examples provided.

Please Share Your Love.

Leave a Reply

Your email address will not be published. Required fields are marked *