File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes While loop and for loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "While loop and for loop" Watch "While loop and for loop" New topic
Author

While loop and for loop

rajeshchowdary rajesh
Greenhorn

Joined: Nov 21, 2007
Posts: 3
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)
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
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.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
bksella sella
Ranch Hand

Joined: Jul 31, 2003
Posts: 32
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.
Bill Shirley
Ranch Hand

Joined: Nov 08, 2007
Posts: 457
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.


Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: While loop and for loop