403 views
I am very confused between these two loops.
Category
asked Dec 7, 2015
edited Dec 11, 2015 | 403 views

Hi,
I will explain some difference between for and for each loop in java..hope it will somewhat clarify your doubt.

Well both are looping and syntax for both..

For syntax:

For(initialization;conditions;increment/decrement)

Foreach syntax:

For(datatype variable: array)

Obviously we can set the initial value and also final value in for loop and apply some conditions also possible..

But in foreach loop we can't set anything.it will process all the values in array or collection.

Consider the following example,

Class forex
{
Public static void main(String args[])
{
Int arr[]={51,52,53,54,55};
System.out.println("for loop output");
For(int i=3;i<5;i++)
System.out.println(arr[i]);
System.out.println("foreach loop output");
for(int j:arr)
System.out.println(j);
}}



Output will be like this,

for loop output
54
55

foreach output
51
52
53
54
55

So, when we want to deal with all elements in array it is better to use foreach loop..

And when we want to deal with some values in array it is better to use for loop...

:More reference :

Find time complexities among for and foreach explained here :
http://jacksondunstan.com/articles/3165

Thank you...

answered Dec 8, 2015 by
edited Dec 10, 2015
good explanation gypsiii
Tanq techdoubt..keep support
+1 vote

A for loop is helpful when you have a sign or assurance, ahead of time, of how frequently you need a circle to run. For instance, in the event that you have to play out a procedure for every day of the week, you realize you need 7 circles.

A foreach loop is the point at which you need to rehash a procedure for all bits of an accumulation or cluster, yet it isn't critical explicitly how often the circle runs. For instance, you are arranging a rundown of most loved books for clients. Each client may have an alternate number of books, or none, and we don't generally mind what number of it is, we simply need the circle to follow up on every one of them.

answered Dec 15, 2018 by