Search Interview Questions | More than 3000 questions in repository. There are more than 900 unanswered questions. Click here and help us by providing the answer. Have a video suggestion. Click Correct / Improve and please let us know. |
|
| ||||
Core Java - Interview Questions and Answers for 'For vs foreach loop' - 1 question(s) found - Order By Newest | ||||
| ||||
Ans. 1. for loop in java is used with a counter as following for(int counter=0;counter < 50;counter++){ System.out.println(list.get(counter)); } for iterating and printing the contents of a collection whereas foreach loop can be specified directly without the use of counter for(String str:list){ System.out.println(list.get(counter)); } 2. for Each loop syntax is more clean if we have to iterate over the elements of a collection and we need not keep track of the record count 3. For is preferred when we need loops without the usage of collections or Array of objects and entirely primitives are being used 4. for loop is preferred if we need to keep track of record count and have to perform some action of the basis of that. For example - If we have to print something after every 5 records, With for each loop in such case, we will have to keep a separate counter. | ||||
Help us improve. Please let us know the company, where you were asked this question : | ||||
Like Discuss Correct / Improve  loop  for loop  control statements  loop statement  foreach loop  for vs foreach loop | ||||
Related Questions | ||||