We can get the same functionality with while loop also..I may have to change the question. Which feature one loop has while the other loop doesn't have it. What I am trying to get is, Do we miss anything if we get rid of one of the loops from Java ?
There is no missing functionality in any of the loops. Its just that using for loop for iterating index elements is easier. Using while loop for the same functionality is possible but the code is ugly and harder to understand for anyone...
Shanky Sohar wrote:if you want to make a code that is more understandable for future developer who see your code and be thankful to you then use for loop
Not correct. Let me fix it:
"If you want to write code that is more understandable for both yourself and for future developers who see your code and be thankful to you, then use whichever loop type makes the most sense in the context of the code."
Sometimes the for loop will be the most readable, sometimes it will be the while loop. Use whechever makes the most sense -- but that's certainly not always the for loop.
For loops should be generally prefered over while, as they are easier to understand and more intuitive.
AFAIR, Bruce Eckel suggested that the for loop should be also prefered because of the granularity of the variables. For loop lets you declare, define and use iteration variable only within the for, which conforms the choose-smallest-available-scope for the variable rule.