• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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

 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:

 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Do not threaten THIS beaver! Not even with this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic