3

I know this question has already been asked multiple times, but my teacher is saying that in Java you should (almost) never use the while loop and use instead the for loop.

So, I haven't find anything that goes in this way. Maybe she saw some kind of Internet nonsense or maybe, long time ago in an old version.

Has the while loop (or has had in some old version) any issues that makes the for loop more efficient?

Little Santi
  • 8,563
  • 2
  • 18
  • 46
Zgravada
  • 87
  • 4
  • 9
    I have never heard about such thing before – Andremoniy Jan 30 '17 at 10:48
  • java 8 still has it, so i dont think is broken or lazy developed.... – ΦXocę 웃 Пepeúpa ツ Jan 30 '17 at 10:48
  • Use of for or while loop totally depends on use case to use case. There nothing like for is better than while. – sAm Jan 30 '17 at 10:49
  • 3
    She's is wrong. `While loop` and `for loop` are two different loops and should be used according to your need. No such thing as poorly optimized `while loop` – Yousaf Jan 30 '17 at 10:49
  • 1
    so you should rather write `for(;not_found;)` instead of `while(not_found)` just to get a potentional 0.0000001 ms performance, if there is even a difference, which i doubt. I´d tell her to grant you a source that supports the claim or ignore it as it looks like nonsense. – SomeJavaGuy Jan 30 '17 at 10:51
  • Seems to be nonsense to me. How did she argument it? – lexicore Jan 30 '17 at 10:52
  • Does she gave any examples? – Ravi MCA Jan 30 '17 at 10:53
  • 3
    Are you sure you did not misunderstand your teacher? You said it yourself, "my teacher is saying that in Java you should (**almost**) never use the while loop". Which implies that your teacher says it is ok to use the `while` loop. And isn't that true? If you know the number of iterations you use a `for` loop, and otherwise a `while` loop. I feel that maybe the teacher was just perhaps expressing it a little badly. – Aidin Jan 30 '17 at 10:53
  • I think your teacher just said that "java enhanced for loop" must to be preferred over a "java while loop" (based on a condition, like Iterator.hasNext() ). That's true due to the readability, use of Generics and easy to avoid infinite loop. "While" loop can be used as you wish, just try to avoid to Iterate over a group (like Collection etc) of Objects – MrPk Jan 30 '17 at 11:03
  • Thank you for your answers, she even says to use a for to iter (with hasNext) instead of a while. I will pick an answer to close the question. – Zgravada Jan 30 '17 at 11:04

0 Answers0