Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

Write a Java program to demonstrate for loop?

A for loop in Java is a control flow statement that repeats a block of code a set number of times. What makes it distinct from other loops is its compact header, which keeps three things together in one line: an initialization that runs once, a condition that is checked before every pass, and an update that runs after every pass. This makes the for loop the natural choice whenever you already know how many iterations you need. The short program below uses a for loop to print the numbers 1 to 5.

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

Output:

1
2
3
4
5

Syntax of the for Loop in Java

The for loop bundles initialization, condition, and update inside a single header, separated by semicolons, followed by the body in braces.

for (initialization; condition; update) {
  // statements to run on each pass
}
  • initialization: runs exactly once before the loop starts, usually to declare and set the loop counter. The variable declared here is scoped to the loop.
  • condition: a Boolean expression checked before every pass. The loop continues while it is true and stops the moment it is false.
  • update: runs after each pass to move the counter toward the value that ends the loop. Forgetting it leaves you with an infinite loop.
  • body: the statements that run on each pass. Without braces, only the next single statement is treated as the body, which is a frequent source of bugs.

How the for Loop Executes

Once you know the order in which the three header parts fire, the behaviour of any for loop becomes predictable.

  • The initialization runs once, setting up the loop counter.
  • The condition is evaluated. If it is false right away, the loop is skipped entirely.
  • If the condition is true, the body of the loop runs.
  • The update statement executes, changing the loop counter.
  • Control returns to the condition and the cycle repeats until the condition becomes false.

Example: Sum of the First N Numbers

Because the counter and its bound live in the header, a for loop is a clean way to accumulate a running total across a known range. Here it adds the numbers 1 through 10.

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

Output:

Sum of 1 to 10 = 55

Example: Factorial Using a for Loop

Counting up from 1 to n and multiplying as you go gives the factorial. A long is used for the running product so it can hold values larger than an int can.

class FactorialDemo {
  public static void main(String[] args) {
    int n = 5;
    long factorial = 1;
    for (int i = 1; i <= n; i++) {
      factorial *= i;
    }
    System.out.println("Factorial of 5 = " + factorial);
  }
}

Output:

Factorial of 5 = 120

Example: Printing a Multiplication Table

Multiplying a fixed number by the changing counter is a classic use of the for loop. This program prints the multiplication table of 5.

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

Output:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Enhanced for-each Loop

When you simply want to visit every element of an array or collection in order, the enhanced for-each loop is cleaner than managing an index by hand. The program below totals an integer array and then prints each item of a List.

import java.util.Arrays;
import java.util.List;

class ForEachDemo {
  public static void main(String[] args) {
    int[] numbers = {10, 20, 30};
    int sum = 0;
    for (int n : numbers) {
      sum += n;
    }
    System.out.println("Array sum = " + sum);

    List<String> tools = Arrays.asList("JUnit", "TestNG", "Selenium");
    for (String tool : tools) {
      System.out.println(tool);
    }
  }
}

Output:

Array sum = 60
JUnit
TestNG
Selenium
  • Use a for-each loop when you only need to read each element in order and do not care about its position.
  • Use a normal for loop when you need the index, want to iterate in reverse, skip elements, or modify the structure while looping.

Nested for Loops for Patterns

Placing one for loop inside another lets you work across two dimensions, which is how grids, matrices, and text patterns are built. The outer loop controls the rows and the inner loop controls the columns. This program prints a right-angled triangle of stars.

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

Output:

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

break and continue in a for Loop

The break statement exits the loop immediately, while the continue statement skips the rest of the current pass and jumps to the update step. The program below loops from 1 to 6, continues past 3 so it is never printed, and breaks out of the loop when it reaches 5.

class BreakContinueDemo {
  public static void main(String[] args) {
    for (int i = 1; i <= 6; i++) {
      if (i == 3) {
        continue;
      }
      if (i == 5) {
        System.out.println("Stopping at 5");
        break;
      }
      System.out.println(i);
    }
  }
}

Output:

1
2
4
Stopping at 5

Infinite for Loops

All three parts of the for header are optional. Omitting the condition makes it permanently true, so for(;;) is a deliberate infinite loop. You exit it from the inside with a break statement when a stop condition is met, which is a common pattern for event loops and retry logic.

class InfiniteForDemo {
  public static void main(String[] args) {
    int count = 0;
    for (;;) {
      count++;
      if (count == 3) {
        System.out.println("Exiting after 3 passes");
        break;
      }
    }
  }
}

Output:

Exiting after 3 passes

for vs while

Both loops repeat a block of code while a condition holds, but they suit different situations. The table below summarizes how they compare, and you can dive deeper in the Java Program to Demonstrate While Loop.

Aspectforwhile
HeaderInit, condition, and update in one lineOnly the condition
Best forA known, counted number of iterationsAn unknown count driven by a runtime condition
Counter scopeCounter is usually scoped to the loopCounter is declared and managed outside
  • Reach for a for loop when counting through a fixed range or array, since the header keeps all the moving parts together.
  • Reach for a while loop when iterations depend on a condition you cannot count ahead of time, like reading input until a sentinel or polling until a flag is set.

Common Pitfalls

  • Off-by-one errors: mixing up < and <= changes how many times the loop runs. Decide whether the boundary value should be included and pick the operator that matches.
  • Stray semicolon after the header: writing for (...); gives the loop an empty body, so the counter spins to the end while none of your intended statements run.
  • Modifying the counter inside the body: changing the loop variable in the body as well as the update step can cause it to skip values or never reach the exit condition.
  • Wrong update direction: incrementing when the condition expects a decrement, or vice versa, pushes the counter away from the exit value and creates an infinite loop.
  • Integer overflow: accumulating large products, such as factorials beyond 12, overflows an int. Use a long or BigInteger for big results.

Once your loop-driven Java logic is correct, you can run the Selenium or unit tests that depend on it across thousands of real browser and OS combinations with Selenium Automation, so behaviour stays consistent everywhere your code runs.

Frequently Asked Questions

What are the three parts of a Java for loop?

A for loop header has three parts separated by semicolons: the initialization runs once before the loop starts, the condition is checked before every pass and keeps the loop running while it is true, and the update runs after each pass to move the loop variable forward. Keeping all three in one place is what makes the for loop ideal for counted iteration.

How is a for-each loop different from a normal for loop?

The enhanced for-each loop iterates directly over the elements of an array or collection without a counter or index. It is shorter and less error prone, but you cannot easily access the index, iterate in reverse, or modify the structure while looping. Use a normal for loop when you need the index or fine control, and a for-each loop when you only need to read each element in order.

Can a Java for loop run zero times?

Yes. The for loop is entry-controlled, so the condition is evaluated before the first pass. If the condition is already false when the loop is reached, the body never executes and control moves straight to the statement after the loop.

How do I write an infinite for loop in Java?

Write for(;;) with all three parts omitted, or leave only the condition empty. Because there is no condition that can turn false, the loop runs forever unless you exit it from inside with a break or return statement, or throw an exception.

What is the difference between break and continue in a for loop?

break immediately exits the nearest enclosing loop, so control jumps to the statement after the loop. continue skips the rest of the current iteration and jumps to the update step, then re-checks the condition for the next pass. break stops looping; continue just skips one pass.

When should I use a for loop instead of a while loop?

Use a for loop when you know the number of iterations in advance, since its header keeps the initialization, condition, and update together for counted ranges and arrays. Use a while loop when the number of iterations is unknown and depends on a runtime condition, such as reading input until a sentinel value.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests