Skip to end of metadata
Go to start of metadata


The Basic for Loop

The Basic for Loop

Java 5.0 introduced a new structured for loop, Called the 'Enhanced for Loop'. For-in, For-Each and Enhanced-For all refer to the same Java construct.

We are not going to talk about the Enhanced for loop on this page but rather the 'Basic for Loop' which we now call the old style of for loop in java.

The for loop has three main declarations:

  1. Declare and initialize a variable.

  2. A boolean expression to test a condition.

  3. Iteration expression.

Pseudo Code
for Loop in Java
Iteration Expression
The iteration expression runs after the body of the loop gets executed. We'll talk more about this later.

Declare and initialize variables.

 Section one of the for loop lets you declare zero or more variables, you separate these variables using commas ( , ).

Multiple Variables

The initialization is the first thing that happens in a for loop and it only happens at the beginning. The iteration expression and the boolean test get executed with each iteration of the loop.

Scope of variables in for loops .

The variable declared inside the for loop is limited to the for loop, i.e. the variable in the for loop stays in and ends with the for loop.

 

Variable Scope Test
The above code will generate the following error:
 
i cannot be resolved to a variable

at forlooptest.main(forlooptest.java:5)  
Variables declared outside the for loop

If a variable is declared outside the for loop but initialized in the for loop can be used outside the for loop.

For e.g.

Boolean Expression.

You are only allowed to have one test expression.

You cannot do multiple tests like other parts of the for loop.

for e.g.

Iteration Expression.

The iteration expression is executed after the body of the loop has been executed, it gives you the choice to say what you want to do after each execution.

There may be times when the iteration expression may not execute due to a forced exit.

Type of breakWhat happens
breakExecution jumps immediately to the 1st statement after the for loop.
returnExecution jumps immediately back to the calling method.
System.exit()All program execution stops; the VM shuts down.

so for example.

For Loop test

 

 

Labels: