+ 4
What are uses of for each loop
3 Answers
+ 3
foreach loop work with collections without bothering about index of the element. It is best when elements in the collection have to be processed sequentially.
for (datatype var : collection ) {
//to
}
example
int arr[] = {1,2,3,4,5,6,7,8,9}
for(int i:arr){
System.out.println(i);
}
+ 1
while loop runs indefinitely. it's used for keeping simple things going. for instance a guessing game would use a while loop to restart after each guess.
for loop has a set amount of loops. It might loop thru a list for example. perhaps you want to add all the numbers from a list together. you would create a variable and use a for loop to look at each item in the list and add it to the variable.
+ 1
foreach loop in Java is known as an enhanced for loop