Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Which are the differences between the three (for, forEach and While)?

 
André Asantos
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which are the differences between the three (for, forEach and While)? Could you give me examples of use?

Thank you,
André AS
 
cheng jian
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All of them are used for loop.
Difference is
Example:
for:we use very often,it used to loop times is clear

print result:01234

forEach:we call it powerfull loop,it can be used to loop object

List<String> listStrings=new ArrayList<String>();

pring result:123

while:the loop has conditions

print result:01234

 
teja dharma
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for,for each,while are used for iterations.
for loop is used if you already know how many times the loop has to executed.
while is used when you do not know the number of times loop has to executed.
for each introduced in 1.5 version is used for iterating only the elements in arrays,collections.
ex:

 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might want to bookmark Sun's Java Tutorials for future reference. With respect to your question, see Learning the Java Language > Language Basics > Control Flow Statements.

Java's For-Each is also known as the "enhanced for statement," which was added with version 5. See The For-Each Loop.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic