While writing a program, in which situation should I use For loop and when to use enhanced for loop? both results same. Is there any situation anyone ever faced ;when you could not get the result using for loop and had to use enhanced for loop or vice versa?
The important difference between them is that for a regular loop you have to manage the array index yourself and in an 'enhanced' for loop, or 'foreach' loop, you do not.
So you might use a regular for loop if knowing the index is important to you in some way. As an example, if you wanted to print out every other item in a list then a regular for loop would make more sense for that.
Oracle documentation wrote:
So when should you use the for-each loop? Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.