+ 2
Difference between for for Loop and Enhanced for Loop with example?
Loops
5 ответов
+ 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.