For Loops in Java




Welcome to the for loops.

This is another type of control structure in java which controls the flow in a program. Previously we have done while loops and dowhile loops.

Having many types of loops doesn’t add any additional power to java. And, FYI, only one type of loop structure is enough to control repetitions in a programming language!

It’s all about the convenience.

Sometimes, one loop may seem to be easier to implement than another. So for loop is also useful and can be used according to the programmer’s preference.

I’ll explain this loop quickly for you. So, here’s the basic structure of a for loop;

for ( <initializer> ; <condition> ; <update>)

{

                <statements>

}

for a single statement, brackets are not needed.

for ( <initializer> ; <condition> ; <update>)

                <statement>

<initializer> is the variable which will update in each cycle.

First, <initializer> variable is created. Then the computer checks the <condition> and if it’s true, the <statement/s> is/are executed.

After finishing the execution of the <statements>, the computer again moves back to the initial “for” statement and updates the <initializer> according to the <update>.

Then, it again checks the <condition>. If <condition> is true, it goes through the <statements> again..

This is repeated until the <condition> becomes false.

If that happens, the computer exits the loop and moves to the code below the for statement block.

Let’s see an example. I’ll take one of the examples that we have studied previously. Printing “Hello World!” statement 10 times.                       

Here,the variable i is called the loop control variable.

First, i is created. In the for loop, the value i is assigned with value 0.

Then the computer checks the condition i < 10. Since this is true as 0<10, “Hello World!” is printed once.

Then the computer moves back to the for statement.

There, it updates the value of i by adding 1 to it and then checks the condition whether i<10. Now i is 1 and as 1<10, the print statement is again executed.

This cycle is repeated until the value of i becomes 10. At that point, 10<10 is false, so further execution of the loop stops.

Ah, of course you can initialize i within the loop itself.

for (int i=0 ; i<10 ; i=i+1)

{

.
.
.

}

But this i is local to the block as we did in the blocks tutorial. This i is not visible outside of this { } block. But the previous i which we declared the variable outside the for loop, is visible to outside. Remember that.

OK. That’s all for for loops. See you in the next tutorial 🙂