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++)
{
System.out.print(j);
}
}
}

 

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

Syntax

For(variable : collection)

{ Statements; }

Example:

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

{
System.out.println(i);
}

Please Share: Tweet about this on TwitterShare on FacebookShare on Google+Share on RedditPin on PinterestShare on LinkedInDigg thisShare on StumbleUponShare on TumblrBuffer this pageShare on VKEmail this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *