The moose likes Beginning Java and the fly likes for and while loops Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "for and while loops " Watch "for and while loops " New topic

for and while loops

Khurram Hussain

Joined: Sep 29, 2001
Posts: 2
which loop is more efficient? for loop or while loop
Michael Fitzmaurice
Ranch Hand

Joined: Aug 22, 2001
Posts: 168
Hi Khurram
What do you mean by 'efficient'? If you are seeking to learn how to use just one and stick to it because it's 'more efficient', that won't work.
The while loop obviously just checks if a condition is true or false, if true then the code of the loop is executed. A for loop normally declares and initialises a variable, checks a condition, if true executes the code of the loop, then typically increments or decrements a counter.
In this respect, you could say it is carrying out more 'work' outside of the block of code in the loop, so 'less efficient'. However, the point is, you would normally use them for slightly differnt purposes, and the logic required would be the overriding factor in deciding which one to use.

"One good thing about music - when it hits, you feel no pain"
Bob Marley

"One good thing about music - when it hits, you feel no pain" <P>Bob Marley
timothy zimmerman
Ranch Hand

Joined: Jun 26, 2001
Posts: 149
As Michael said the factor that should determine which looping method you use depends on what it is you are tyring to accomplish.
The for loop is typically controlled by a counter (although you could use differently) so you might use it when you know how any times you want to repeat logic within the loop (ie you want to list the contents of an Array).
int numberOfIterations = myArray.length;
for( int counter = 0; counter < numberOfIterations; counter++)
// statements
The while loop evaluates a given expression and if it is true executes the code within the loop while that condition remains true. This would be useful if you don't know how many times you will need to execute the loop. One example of this would be the run() method. You would want to continue looping until some condition dictates otherwise.
keepRunning = true;
while( keepRunning
// whatever you want do do while running
// loop keeps executing until the value of keepRunning changes

There is also the do while loop. This is very similar to the while loop execpt that the logical expression is evaluated at the end of the loop rather than the beginning. This means that the code within the loop will be executed at least once even if the condition is false.
// statements
while( expression )
Hope this helps.
Dan Lund

Joined: Jul 17, 2001
Posts: 26
i use just for loop`s just sometimes while loop`s...........
I agree. Here's the link:
subject: for and while loops
It's not a secret anymore!