Java enhanced for Loop
Java5 introduces an enhanced for loop that is primarily used for arrays .
The Java enhanced for loop syntax format is as follows :
( in simple terms, the elements in the array are sequentially output )
for ( declaration statement : expression )
{
code sentences
}
declaration statement: declares a new local variable that must have a type that matches the type of the array element. Its scope is scoped to the Loop statement block, whose value is equal to the value of the array element at this time.
expression : The expression is the name of the array to access, or is the method that returns the value to the group.
Instance:
Public class Test1 {
Public Static void Main (string[] args) {
int [] numbers={10,20,30,40,50};// defines an array
for (int x:numbers) {// enhanced for Loop, which sequentially outputs the elements in the array
System. out. Print (x);
System. out. Print (",");
}
System. out. Print ("\ n");
String[] names={"James", "Larry", "Tom", "Lacy"};// definition array
for (String name:names) {// enhanced for Loop, which sequentially outputs the elements in the array
System. out. Print (name);
System. out. Print (",");
}
}
}
Java Enhanced for loop