What is the difference between for and foreach loop in java ? Which one should be used in which cases ?<br /> <br />
Javasearch.buggybread.com

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.
Label / Company      Label / Company / Text

   



Interview Questions and Answers

 Q1. What is the difference between for and foreach loop in java ? Which one should be used in which cases ?

Core Java
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




Help us and Others Improve. Please let us know the questions asked in any of your previous interview.

Any input from you will be highly appreciated and It will unlock the application for 10 more requests.

Company Name:
Questions Asked: