Where to use for and foreach statements in java programming | exapmles

By | June 18, 2012

The enhanced for statement cannot be used in some common situations. It has got some drawbacks

1. Only single structure – It’s not possible to traverse two structures at once, eg, to compare two arrays.

2.Only single element – Use only for single element access, eg, not to compare successive elements.

3.Only access – Elements can not be assigned to, eg, not to increment each element in a collection.

4.Only forward – It’s possible to iterate only forward by single steps.


For loop combines three elements which we generally use: initialization statement, boolean expression and increment or decrement statement.

For loop syntax

for( <initialization> ; <condition> ; <statement> )


<Block of statements>;
  • The initialization statement is executed before the loop starts. It is generally used to initialize the loop variable.
  • Condition statement is evaluated before each time the block of statements are executed. Block of statements are executed only if the boolean condition evaluates to true.
  • Statement is executed after the loop body is done. Generally it is being used to increment or decrement the loop variable.

An example of for statement

public class testFor
public static void main(String [] args)
for (int i=1; i<=9; i++)
for (int j=1; j<=i; j++)


JDK 5.0 provides a special kind of for loop for access through all the elements of it.


For(variable : collection)

{ Statements; }


int[] a={1,2,3,4,5,6,7,8,9,0};
for(int i : a)


Author: Ravi Bandakkanavar

A Techie, Blogger, Web Designer, Programmer by passion who aspires to learn new Technologies every day. It has been 6 years since I have been publishing articles and enjoying every bit of it. I want to share knowledge and build a great community with people like you.

Suggested read for you:

Did it help? Comment here..