1

I just stumbled upon this question Are "while(true)" loops so bad?
They made me think what do I normally do.And to my surprise I realised that I have almost never used a while loop in my professional code(or work code) .
Front end frameworks e.g faces etc do not count.
So When should I use a 'while loop'? and How often do you use while loop?
It's is a real question please do not close as being subjective I really am after a concrete example.where it can not be replaced with a better alternate.

Community
  • 1
  • 1
Java Ka Baby
  • 4,880
  • 11
  • 39
  • 51
  • 1
    That question is about specific case of `while` which is `while(true)`, but `while` in general, you can use it any time, behind the scenes it's almost exact to `for` loop. – mohdajami Sep 08 '11 at 10:45
  • 1
    Indeed, please don't confuse `while (true) {}` (which is an infinite loop which is by some developers considered poor practice) with `while (someSpecificConditionWhichIsNeverUnchanged) {}` (which is perfectly fine). – BalusC Sep 08 '11 at 21:14

7 Answers7

7

One place where I might use it is where you need to treat the first element of a sequence differently to the rest. That makes a foreach loop awkward, but a while loop works well:

Iterator<String> iterator = foo.iterator();

// Handle the first item specially
if (!iterator.hasNext()) {
    throw new SomeException("foo shouldn't be empty");
}
SomeResult result = new SomeResult(iterator.next());

// Now deal with the rest
while (iterator.hasNext())
{
    String item = iterator.next();
    result.addItem(item);
}

Also I use a while loop as one of the few places where I'll also include an assignment in a condition:

String line;
while ((line = reader.readLine()) != null)
{
    // Handle the line
}

or with an InputStream:

int bytesRead;
while ((bytesRead = input.read(buffer)) != -1)
{
    // Handle the buffer
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Accept 'readLine' example it does need it.True usage.But do you think iterators are still used these days.This statement is also more of a question than argument. – Java Ka Baby Sep 09 '11 at 00:11
  • @Java Ka Baby: They're used a lot, yes - but usually within an enhanced for loop. Occasionally it's useful to treat the first item differently (e.g. to get an initial value when you're trying to find a maximum/minimum) and at that point, doing it manually can sometimes be the simplest approach. (This is true in C# too.) – Jon Skeet Sep 09 '11 at 05:27
3
java.util.Scanner scanner = //...

while(scanner.hasNextLine()) {
  String line = scanner.nextLine();
  //..do sth with the line
}

In fact every while loop can be replaced with for. But e.g. in the code above it would be less readable - and that's the point: use while when it fits better to the nature of the problem.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
1

You should use it to loop while some condition holds true.

John Topley
  • 113,588
  • 46
  • 195
  • 237
1

Simple never-stopping backend logic:

while (true) {
  consumeMessage();
}

Or also

for (;;) {
  consumeMessage();
}
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
1

You should use it when you dont know how many iterations will be needed. You only know that you want to do something while your condition is met. It could be itereated 2, 100, 0... times.

Martin Gamulin
  • 3,855
  • 21
  • 25
1

Of course you can always rewrite a while loop into a for loop, but often it is uglier, meaning that parts of the for (..;..;..) are left blank - mainly the initialization. Findbugs also gives a warning in this case: similar to "simple for loop detected, rewrite it as a while loop".

The main application of the while loop is that you do not need an initialization, or want to treat the first loop iteration (e.g. first element of an enumeration) specially, in which case you do the initialization beforehand, too.

DaveFar
  • 7,078
  • 4
  • 50
  • 90
0

Use it when you have a main loop in your code which you want to run until something changes.

When you dont need a counter, and when you dont need to iterate over a collection (because then you need a counter).

Using a for(;whatever;) is ugly code, thats where you have to use a while.

Also the variation, do ... while allows you to do something at least once and then possibly many times.

rapadura
  • 5,242
  • 7
  • 39
  • 57