Enhanced for loop
The enhanced for loop allows you to iterate through a collection without having to create an Iterator or without having to calculate beginning and end conditions for a counter variable. The enhanced for loop is the easiest of the new features to immediately incorporate in your code. In this tip you will see how the enhanced for loop replaces more traditional ways of sequentially accessing elements in a collection.
Syntax: for (int i : squares)
squares means object
Here is a short program, OldForArray, that uses the for loop.
public class OldForArray {
public static void main(String[] args){
int[] squares = {0,1,4,9,16,25};
for (int i=0; i< j =" 0;" squares =" {0," style="font-weight: bold; color: rgb(153, 51, 0);">Altho the enhanced for loop can make code much clearer, it can't be used in some common situations.
Only access. Elements can not be assigned to, eg, not to increment each element in a collection.
Only single structure. It's not possible to traverse two structures at once, eg, to compare two arrays.
Only single element. Use only for single element access, eg, not to compare successive elements.
Only forward. It's possible to iterate only forward by single steps.
At least Java 5. Don't use it if you need compatibility with versions before Java 5.
Enhance for loop in java,servlet,jsp,struts
No comments:
Post a Comment