+3 votes
335 views
I am very confused between these two loops.
asked Dec 7, 2015 in Computer Science - IT by Salman (10 points)
edited Dec 11, 2015 by slow_learner | 335 views

1 Answer

+5 votes

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 gypsiii (353 points)
edited Dec 10, 2015 by slow_learner
good explanation gypsiii
Tanq techdoubt..keep support