Next-Gen App & Browser Testing Cloud
Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

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
5The 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
}Once you know the order in which the three header parts fire, the behaviour of any for loop becomes predictable.
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 = 55Counting 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 = 120Multiplying 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 = 50When 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
SeleniumPlacing 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:
*
**
***
****
*****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 5All 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 passesBoth 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.
| Aspect | for | while |
|---|---|---|
| Header | Init, condition, and update in one line | Only the condition |
| Best for | A known, counted number of iterations | An unknown count driven by a runtime condition |
| Counter scope | Counter is usually scoped to the loop | Counter is declared and managed outside |
for (...); gives the loop an empty body, so the counter spins to the end while none of your intended statements run.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.
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.
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.
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.
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.
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.
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.
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