Friday, January 4, 2008

Iteration in JAVA, the extended "for"

Iteration:
think of a situation where we need to print or manipulate a collection or an array of objects. For that we have to access each object of the collection or array, which we can do using loops (for, while, do-while), mostly we use for loop.

Ex1.
int num[] = new int[]{1,2,3,4,5,6,7,8,9};

for(int i=0; i< num.length; i++
System.out.println (n);

Since JAVA 5 for has been extended, now there is no longer the need of iterator (on the above example 'i' is the iterator). We can now use the short form of for.

Ex2.
int num[] = new int[]{1,2,3,4,5,6,7,8,9};

for(int n : num)
System.out.println (n);

1 comment:

grenarios said...

heheheh. he is crazy guy.hahahahhahah