I am learning java as well android. Almost everything that we can perform by while loop those things we can do in for loop.
I found a simple condition where using while loop is better than for loop
if i have to use the value of counter in my program then i think while loop is better than for loop
Using while loop
int counter = 0;
while (counter < 10) {
//do some task
if(some condition){
break;
}
}
useTheCounter(counter); // method which use that value of counter do some other task
In this case I found while loop is better than for loop because if i want to achieve the same in for loop i have to assign the value of counter to another variable.
But is there any specific situation when while loop is better than for loop
No. There's not a specific situation where
for
is better thanwhile
.They do the same thing.
It's up to you choose when apply one of those.
One thing I feel I should point out is that when you use a for loop, you do not need to assign counter to another variable. For example
for(counter=0; counter<10; counter++)
is valid Java code.As for your question, a for loop is usually better when you want a piece of code to run a certain number of times, and a while loop is better when the condition for the code to keep running is more general, such as having a boolean flag that is only set to true when a certain condition is met in the code block.
You can do something like:
Anything that a while-loop can do, can also be done in a for-loop, and anything a for-loop can do, can also be done in a while-loop.
The while loop is generally better when you don't have an iterator (counter usually).
while
loops are much more flexible, whilefor
loops are much more readable, if that's what you're asking. If you are wondering which one is faster, then look at this experiment I conducted concerning the speed offor
andwhile
loops.https://sites.google.com/a/googlesciencefair.com/science-fair-2012-project-96b21c243a17ca64bdad77508f297eca9531a766-1333147438-57/home
while
loops are faster.One main difference is
while
loops are best suited when you do not know ahead of time the number of iterations that you need to do. When you know this before entering the loop you can usefor
loop.