For loop in Java

A for loop repeatedly executes the same set of instructions until the controlling condition is true. It is more compact than the while loop but is equally powerful.


Syntax

The general form of the for loop is:

If the loop body has only one expression then the curly braces are not needed.

For loop has three sections separated by semi-colon:

  • initialization :
    • When the loop starts, the initialization portion of the loop is executed. It is used to set the initial value for the loop control variable.
    • It is executed only once, when the control enters the loop for the first time.
  • condition :
    • It is a boolean expression. If this expression evaluates to true then the control enters the loop else loop terminates.
    • Condition is always tested at the beginning of the loop again and again.
  • iteration :
    • Here, the values of loop control variables are altered according to the requirements.
    • iteration statements are executed at the end of the loop.

Control Flow Diagram of the for loop

When the control enters the for loop, the stepwise execution is :

  1. Statements in the initialization section are executed and work of this section is done. It will not execute anymore.
  2. Now the condition is evaluated.
    1. If true, loop body is executed.
    2. If false, Loop terminates.
  3. At the end of the loop body, iteration statements are executed. Now control goes to the top of the loop; condition is tested, loop body is executed, and so on.

Control Flow Diagram for for loop is given below:

for loop in Java
for loop

An Example

An example would be right to explain all these:

The output is:

The example works as follows:

  • When the loop starts, i is initialized to 0, then condition i<10 is tested which is true, so loop body is executed. After that i is increased to 1,
  • After 1st iteration, i=1, condition i<10 is tested, which is again true. So the loop executes.
  • After 2nd iteration, i=2, condition i<10 is tested, which is again true. So the loop executes.
  • After 9th iteration, i=9, condition i<10 is tested, which is again true. So the loop executes.
  • After 10th iteration, i=10, condition i<10 is tested, which is false. So loop terminates and statement after the for loop is printed.

Declaration of loop control variable inside the for loop

Sometimes the loop control variables are not needed outside the for loop. In those cases, Java provides us with the option to declare the variables inside the initialization section of for loop itself. But this variable will not be accessible outside the for loop beacuse its scope is limited to the this loop. Its scope starts when for loop starts and it ends when the loop terminates.

The same code can be re-written as:

It produces the following output:

Notice one thing here: Since i is not required outside the for loop, it was declared and initialized in the initialization section itself. Because of this, it won’t be accessible ouside the for loop. If you want to use it outside, declare it outside and initialize it in the initialization section like in the previous example.


Use of comma in for loop

Sometimes the initialization section or the iteration section needs more than one variable. So java allows us to use multiple statements in these two sections, separated by commas.

The output is :

 


Some variations of the for loop

The three parts of the for loop (initialization, condition, iteration) are quite flexible. All three or any two or any one of these can be absent.

  • If the condition part is absent, it works like an infinite for loop. However you can still use break to get out of the loop.

    The output is:
  • If the iteration part is absent then it is handled somewhere inside the body of the for loop.
  • If the initialization part is absent then it is set outside the for loop. It is useful in situations when the initial conditions are set by other parts of the program, or by input from the user etc. In the example below, the value of i is set manually to 0 for simplicity.

    The output is:

 


Empty Loop Body

A null statement (only semi-colon) is a valid loop body. When the loop control variables themseves can handle the computation expected from the loop, loop body is unnecessary. In the example below, when the loop ends, j is at least as large as i.

The output is :

 


Processing Array with for loop

Most of the time arrays are accessed using an integer variable which acts as an index on the postion of elements in the array. This index increases uniformly and linearly.

So to access large number of (or all) elements of the array we can use loops. This way, the code is efficient and compact.

The output is:

 


Nesting of for loops.

If one for loop contains another for loop inside its body then loops are said to be nested. This nesting can go to any level. The code below shows two-level nesting i.e two for loops are nested one-inside another:

The output is:

Note that you could have easily replaced any of the for loops with some other loop, say while-loop or do-while loop.


Use of break in for loop

There are occasions when you no longer want to iterate over all the elements because some condition has already been met. In those cases, you have to terminate the loop prematurely. break is a keyword used specifically for this purpose.

The output is:

As soon as the given value is found, loop terminates.

break, takes you out of the loop by one level. Had there been another loop surrounding the for loop in previous example, internal loop would have been broken but the control would have still been surrounded by the external loop. Depending on the need, you might have used another break.


Use of continue in for loop

Sometimes you want to skip rest of the instructions in a loop but you still want to continue running the loop, continue is a statement made specifically for this purpose .

The output is :

In case when i is divisible by 2, the continue statement sends the control to the iteration portion. Then the condition is checked and statements in the for loop execute again from the start.


Labelled for loop

You can label a for loop using any valid Java token followed by a colon. Like in:

Labelling can be used for many uses. For example, break with a label can be used to break out of a series of nested loops to the end of the label.

The output is :