• 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

While loop and for loop

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
what is the need of creating two loops while and for? what is the difference between the two?one is sufficient to do the functionality then wht is the need of other?(interview question faced by me)
 
Ranch Hand
Posts: 1970
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Really, of course, there are three loop constructs in Java. There's "for() { }", "while() { }" and "do { } while()".

It is true that any loop could be implemented with any of the types of loop construct. However, having them both allows code to be clearer and more concise. That is, once the developer is sufficiently experienced to allow them to choose the best loop construct for each circumstance.

In general, "for" is for looping a known number of times, "while" is for looping until a condition is met, and "do while" is shunned.
 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just to give you some more information, the FOR and WHILE loops can be skipped entirely, if the condition specified is not met, whereas "DO WHILE" loop will be executed at least once before the given condition is checked.
 
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The quick answer is that the readability of your code will be better if you use the type of loop that most represents what you are trying to do. (The long answer would show examples of all of those.)

Also note, the new version of java has a second for loop. The original "for (; {}" and the new "for ( {}". The new provides a shorthand for iterating over collections and arrays. See yesterday's post on the topic.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic