This control statements create loops in you program. Execute same instruction/s until a certain condition is met. There are 3 different type of iteration statements:


The while execute the code while the condition is true.

while(condition) {

Here how it works: while the condition is true execute statement1. This means that if the condition is never true the statement1 will never execute.


The do-while loop is very similar to while, exept that it execute always at least the first time the statement, even if the condition is false:

} while(condition);

Execute the first time statement1, than check if the condition is true and repeat the loop.


There are two different type of for loops. The first one, the more “traditional” is this


for(initialization; condition; iteration){


Initialization is usually a control variable, a counter that control the loop. Then the condition is checked and it usually check the control variable. Then it’s executed the iteration, that increment or decrementthe counter.Here an example:

for( x = 0; x < 10; x++)



You can use the for loop also without initialization, condition and iteration:


for( ; ;)


In this second case you will have an infinite loop, means that it will never ends.


The second for type is similar to the foreach of other programming languages. It work like this

for(type variable: collection)


the loop iterate through the collection, for example an array and pass the value to the variable. Here is an example:

int var[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for(int v: var)


In this case the for iterate through the array named var and pass each value to the variable  v and then it print the value.


Everyone of these loops statements can be nested as you want, you can have for example a for loop inside another for retrive data from a multidimensional array.

Categories: Java

Leave a Reply

%d bloggers like this: