Java For Loop

The for-loop statement in Java provides a compact way to iterate over the arrays or collection types using a counter variable that is incremented or decremented after each iteration. Programmers often refer to it as the traditional “for loop” because of the way it repeatedly loops until a particular condition is satisfied.

Note that Java also provides a more concise way to iterate over arrays or collections using the enhanced for-each loop.

1. Syntax

The general form of the for loop can be expressed as follows:

for (initialization; termination; increment) {

    statement(s);
}
  • initialization expression initializes the loop; it is executed once when the loop begins.
  • termination expression provides the condition when evaluates to false, the loop terminates.
  • increment expression is invoked after each iteration; it is perfectly acceptable for this expression to increment or decrement a counter variable.
  • statements are instructions executed in each iteration of the loop. We can access the current value of the counter variable in this block.

Note that all expressions in the for-loop are optional. In case, we do not provide the termination expression, we must terminate the loop inside the statements else it can result in an infinite loop.

2. Java For-loop Example

In the following program, we are iterating over an array of int values. The array contains 5 elements so the loop will iterate 5 times, once for each value in the array.

int[] array = new int[] {0, 1, 2, 3, 4};

for(int i = 0; i < array.length; i++) {

  System.out.format("Value at index %d is %d \n", i, array[i]);
}

Program output.

Value at index 0 is 0 
Value at index 1 is 1 
Value at index 2 is 2 
Value at index 3 is 3 
Value at index 4 is 4 

The execution of for-loop flows like this-

  • First, 'int i = 0' is executed, which declares an integer variable i and initializes it to 0.
  • Then, condition-expression (i < array.length) is evaluated. The current value of I is 0 so the expression evaluates to true for the first time. Now, the statement associated with the for-loop statement is executed, which prints the output in the console.
  • Finally i++ is executed that increments the value of i by 1. At this point, the value of i becomes 1.
  • Again the conditional expression is evaluated as still true, and the print statement is executed.
  • This process continues until the value of i becomes 4, and the print statement is executed.
  • After that, i++ sets the value of num to 5, and the expression i < array.length returns false and stops the execution and terminates the loop.

3. Initialization, Termination, and Increment Statements are Optional

As mentioned in syntax, the initialization, termination, and increment are optional parts, that can be controlled from other places. Or the for loop might not have all of them.

For example, we can rewrite the previous example as below. We have taken out the counter initialization before the loop. We have moved the counter increment and the termination statements inside the loop body. The statements are the same as the previous version.

int[] array = new int[]{0, 1, 2, 3, 4};

int i = 0;
for ( ; ; ) {

  System.out.format("Value at index %d is %d \n", i, array[i]);

  i++;
  if (i >= array.length) {
    break;
  }
}

The program output is the same as the previous version.

Value at index 0 is 0 
Value at index 1 is 1 
Value at index 2 is 2 
Value at index 3 is 3 
Value at index 4 is 4 

Moreover, it is also possible to write an infinite loop without these parts at all:

for (;;) {
    // do something
}

4. Nested Loops

It’s possible to nest one for-loop in another for-loop. This approach is used to process multidimensional structures like tables (matrices), data cubes, and so on.

As an example, the following code prints the multiplication table of numbers from 1 to 9 (inclusive).

for (int i = 1; i < 10; i++) {
    for (int j = 1; j < 10; j++) {
        System.out.print(i * j + "\t");
    }
    System.out.println();
}

Program output:

1   2   3   4   5   6   7   8   9  
2   4   6   8   10  12  14  16  18  
3   6   9   12  15  18  21  24  27  
4   8   12  16  20  24  28  32  36  
5   10  15  20  25  30  35  40  45  
6   12  18  24  30  36  42  48  54  
7   14  21  28  35  42  49  56  63  
8   16  24  32  40  48  56  64  72  
9   18  27  36  45  54  63  72  81 

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode