The for loop is used to iterate the statement or a part of the program several times.
There are two forms of the for loop in java.
1. Traditional for loop
2. For-each loop
1. Traditional For Loop
Syntax of the traditional for loop is:
for(initialization ; condition ; increment/decrements)
{
//statements
}
When the loop first starts , the
initialization portion of the loop is executed.It is important to know that the
initialization statement is
only executed once.Next ,
condition is evaluated.This must be a
Boolean expression.It checks the
loop control variable against
a target value.If this expression is true , then the body of loop is executed otherwise terminates the loop.Next, the
increment/decrements portion executed which is increments or decrements the loop control variable.
After
first pass the loop iterates , first evaluated the
conditional statements ,then executing the body of loop and then executes the
increments/decrements portion.This process repeats until the
condition false.
Flow Chart Of Traditional For Loop:
Simple program of traditional for loop:
package org.modi;
public class Test
{
public static void main(String[] args)
{
for(int i=0;i<5;i++)
{
System.out.println("loop body " + i );
}
}
}
OUTPUT
loop body 0
loop body 1
loop body 2
loop body 3
loop body 4
2. For-each Loop
The for-each loop was introduce in JDK 5(1.5) version of java.The for-each loop is also know as enhanced for loop.The for-each specially designed for iterate the collection of objects , such as an array.It iterate all the elements from starting element to last element.We can con control the number of iteration it iterate all the elements one by one.
Syntax of for-each loop:
for(type variable : collection)
{
//statements
}
Here, type specifies the type (e.g. String , int ) and variable specifies the name of the iteration variable that will receive the elements form the collection , one at a time from begin to end.The collection is the collection of elements which will be iterated by the loop.
Simple program of the for-each loop:
package org.modi;
public class Test
{
public static void main(String[] args)
{
int[] arr={0,1,3,4};
for(int itr : arr)
{
System.out.println("loop body " + itr);
}
}
}
OUTPUT
loop body 0
loop body 1
loop body 3
loop body 4
Some Important points:
1. If for loop body contains only one statement then , no need for curly braces.
E.g.
for(int i=0 ; i< 5 ; i++)
System.out.println("Hello World!");
2. If we declare a variable inside for loop , then the scope of the variable ends with ends of for loop.
3. To create infinite loop leave all the parts of for loop empty.
E.g.
for( ; ; )