Basil
Basil

Reputation: 145

what is the difference between executing For loop Java

Could you tell me, what is the difference between For Loop Java in Code A and B? while both of them gives a same result in executing? and i know what they are doing, but why is For loop written this way in the code *A* Thanks

The code

//Code A
public class MyArray {
  public static void main (String[] args){

  int[] a ={1,10,30,40,50};

  for (int i : a)
  {
      System.out.println(i);
  }

 }
}
//====================================
//Code B

public class MyArray{
  public static void main (String[] args){

  int[] a ={1,10,30,40,50};

  for (int i=0;i< a.length; i++)
  {
      System.out.println(a[i]);
  }

 }
}

Upvotes: 3

Views: 140

Answers (6)

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28528

Actually both codes are equal as first code if in the right-hand side of the for(:) array rather than an Iterable object (as in this case), the internal code uses an int index counter and checks against array.length. which is equivalent to:

for (int i=0;i< a.length; i++)
{
   System.out.println(a[i]);
}

Advantage of first code is its internally handle the end condition and short in writing then the second one.

but if object is iterable then it converts to:

for(Iterator<String> i = iteratableObject.iterator(); i.hasNext(); ) {
    String item = i.next();
    System.out.println(item);
}

Upvotes: 1

Justin
Justin

Reputation: 25277

The answers here have not pointed to a certain vital difference: in code A, you cannot simply change the elements of the array, because the i is just a reference, while in code B, you can do a[i] = //something.

If your array was an array of some Objects and you just wanted to use Mutability, then there is no difference.

Upvotes: 1

Junaid Shirwani
Junaid Shirwani

Reputation: 336

The shorter version of the for loop means for each index in the array, which quite simply is easier to understand. The other for loop is a most commonly used which starts from a assigned starting value and goes on till the end of array. The selection depends on the situation according to me. There might be a time when using the codeA format would give a better understanding to the one who debugging the application.

Upvotes: 1

dev2d
dev2d

Reputation: 4262

Iterating over a collection is uglier than it needs to be. Consider the following method, which takes a collection of timer tasks and cancels them:

void cancelAll(Collection<TimerTask> c) {
    for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); )
        i.next().cancel();
}

The iterator is just clutter. Furthermore, it is an opportunity for error. The iterator variable occurs three times in each loop: that is two chances to get it wrong. The for-each construct gets rid of the clutter and the opportunity for error. Here is how the example looks with the for-each construct:

void cancelAll(Collection<TimerTask> c) {
    for (TimerTask t : c)
        t.cancel();
}

for each is just a better way of iterating.

Limitation: in for-each loop you will not be able to know which number of element(index of the element in collection) you are processing, you need to define counter for the same, while in simple for loop i tells you the number of the element you are processing.

Upvotes: 4

geoand
geoand

Reputation: 63991

Code A by is just syntactic sugar for code B and works on Java versions 5 or later. The advantage is that you do not have to handle the mundane indexing code on your own. Code A is also known as the foreach loop

Plus Code A also works if instead of int[] you had a Collection, thus giving you a uniform way of iterating over arrays and collections (or to be ever more precise, any subclass of Iterable)

Upvotes: 2

Alex Salauyou
Alex Salauyou

Reputation: 14338

Practically, no difference, but code A is easier to read and harder to make a mistake.

Upvotes: 1

Related Questions