Computersight > Programming > Java

The Generic for Loop

The basic for loops in the Java 1.4.x and Java 1.5.

I would like to share a basic things on the modified “for” loops in the java 5.

The “For Loop” is a loop used to iterate the group of statements.

The general syntax of the “For” loop:

for (initialization; condition; increment or decrement)

{

//statements here

}

Initialization: This part is used to initialize the variable.

Ex: int i = 0;

Condition: This part is used to declare the condition. If the condition fails, it will not execute the statements in the loop.

Ex: i<10;

Increment or Decrement: This part is used to increment or decrement value of the declared variable previously.

Ex: i++; or i--;

We can implement the “for” loop in different ways. We can eliminate the any part (initialization, codition, or increment or decrement) from the loop. But my main focus is that how to use the basic “for” loop in the java 1.4.x and 1.5.

Example: Print the number from 1 to 100;

//declare the class

public class NaturalNum

{ //declare the main method

public static void main (String args[])

{

//declare the variable

int natNum = 100;

//for loop (initialization; condition; increment)

for (int number = 1; number <= natNum; number++)

{

//print the numbers

System.out.println(number);

}

}

}

The above loop is the common “For” loop used in the java 1.4.x. The java5 introduces new “For” loop with generics. Please see the following examples.

The older version of the “for” loop:

public void printNames(Collection names)

{

Iterator namesIterator = names.iterator();

for (int ptr=0; ptr < names.size(); ptr++)

{

String name = (String) namesIterator.next();

System.out.println(name);

}

}

The newer version of the “for”(generics) loop:

//The collection should be declared like below

// Collection names;

public void printNames(Collection names)

{

for ( String name : names)

{

System.out.println(name);

}

}

In newer version, the JVM will implement the iterator stuff. It will reduce the overhead of using iterators. But we will not escape iterators every time. If you want to modify or remove the value from the Collection, We need iterator for that. Using generics, we can not modify or remove the value from the collection.

4
Liked It
I Like It!
Related Articles
Loops in Java  |  Loops in Blitz
More Articles by gadangi
Story of the JDBC Drivers  |  Compare String, Stringbuffer and Stringbuilder
Latest Articles in Java
Basic Java  |  Story of the JDBC Drivers
Comments (2)
#1 by vani, Jun 16, 2008
Very nice for java learners.
#2 by ramu, Jun 16, 2008
Good Article
Post Your Comment:
Name:  
Copy the code into this box:  
Inside Computersight

Communication & Networks

 /

Computers

 /

Hardware

 /

Operating Systems

 /

Programming

 /

Software


Popular Tags
Popular Writers
Computersight
About Us
Terms of Use
Privacy Policy
Services
Submit an Article
Advertise with Us
Contact

© 2007 Copyright Stanza Ltd. All Rights Reserved.