Java for each loop array object traversal
Syntax
For (type itr-var: iterableobj) statement-block
View traversal array instances
Public class mainclass {
Public static void main (string args []) {
Int nums [] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
For (int x: nums ){
System. out. print (x + "");
X = x * 10; // no effect on nums
}
System. out. println ();
For (int x: nums)
System. out. print (x + "");
System. out. println ();
}
}
Output
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Traverse enum objects
Public class mainclass {
Enum season {
Spring, summer, fall, winter
}
Public static void main (string [] args ){
For (season: season. values ()){
System. out. println ("the season is now" + season );
}
}
}
Result
The season is now spring
The season is now summer
The season is now fall
The season is now winter
Traverse arraylist
Import java. util. arraylist;
Public class mainclass {
Public static void main (string args []) {
Arraylist <double> list = new arraylist <double> ();
List. add (1, 10.14 );
List. add (1, 20.22 );
List. add (1, 30.78 );
List. add (1, 40.46 );
Double sum = 0.0;
For (double itr: list)
Sum = sum + itr;
System. out. println (sum );
}
}