+ 2
Difference between for for Loop and Enhanced for Loop with example?
Loops
5 Answers
+ 2
Check this article
http://easybix.com/difference-loop-and-enhanced-loop-java/
+ 2
For loop and enhanced for loop work same but difference in their syntax...
Code
int a[ă={1,2,3,4,5};
/*for loop code*/
for(int i=0;i<5;i++)
{
System. out.println(a[ÂĄ]);
}
/*enhanced for loop example */
for(int b:a)
{
System. out.println(b);
}
+ 1
Ajay in the enhanced for loop can we initialize b to a specific array element?
0
an enhanced for loop can be translated to âForeach/element/in/elementsâ or for example:
String lines[] = {âhelloâ, âhiâ, âheyâ};
for(String line : lines) {
System.out.println(line);
}
line being the element, the semicolon being âinâ and lines being the array of elements. So each time it loops it will print out each element in the lines array:
hello
hi
hey
this is just essentially an easier or âenhancedâ way of using the standard for loop to produce the same outcome:
String[] lines = {âhelloâ, âhiâ, âheyâ};
for(int i = 0; i < lines.length; i++){
System.out.println(lines[i]);
}
the enhanced for loop is best used for iterating through a list/array/collection, whereas the standard for loop would be best when you know exactly how many times youâre going to be looping through a block of code.