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:

While

The while execute the code while the condition is true.

while(condition) {
   statement1
}

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.

do-while

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:

do{
   statement1
} while(condition);

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

for

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

 

for(initialization; condition; iteration){
   statement1

}

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++)

System.out.println(x);

 

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

for(;condition;)

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)
{
   statement1
}

 

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)
{
   System.out.println(v);
}

 

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: