3

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]);
  }

 }
}
sakura
  • 2,249
  • 2
  • 26
  • 39
Basil
  • 145
  • 1
  • 1
  • 9
  • 4
    code A: shorter way of writing some loops since JDK >= 5 – Mik378 Apr 06 '14 at 17:51
  • There's no difference in your example. If you needed to change values in the array, then a standard `for` loop would be much easier to use. – PM 77-1 Apr 06 '14 at 17:53
  • 1
    Check this post: http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work; there is some difference as you can see, in particular if you are trying to modify the array () – Trinimon Apr 06 '14 at 17:54
  • 1
    And with Java 8 Streams: Integer[] a ={1,10,30,40,50}; Arrays.asList(a).stream().forEach((i) -> System.out.println(i)); – Raul Guiu Apr 06 '14 at 18:00

6 Answers6

4

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.

dev2d
  • 4,245
  • 3
  • 31
  • 54
  • Thanks for the answer. Please would you tell me, Are Arrays necessary to use at all applications that written to do kind of function? – Basil Apr 06 '14 at 19:36
  • Did not get your question! – dev2d Apr 06 '14 at 19:39
  • Sorry for that, i wanted to say that, when can i use arrays when? and what is kind of applications need for arrays when it written in java? – Basil Apr 06 '14 at 20:29
  • 1
    it depends on the requirement of your code, basically when you want fixed sized collection you can use `Array` and when variable sized collection `ArrayList` has to be used, similarly you can check for other data structures, when to use what? visit http://www.sergiy.ca/guide-to-selecting-appropriate-map-collection-in-java/ – dev2d Apr 07 '14 at 06:19
2

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)

geoand
  • 60,071
  • 24
  • 172
  • 190
  • Thank a lot for the useful answers , so another think i really would to know in code A dose any effect on running of executing time? – Basil Apr 06 '14 at 18:08
  • @Basil As far as I know, there is no effect whatsoever because the compiler turns the foreach statement into pretty much the same byte code as I does for the for loop – geoand Apr 06 '14 at 18:12
1

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

Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
1

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.

Justin
  • 24,288
  • 12
  • 92
  • 142
1

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.

Junaid Shirwani
  • 360
  • 1
  • 6
  • 20
1

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);
}
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
  • Thanks for the answer. Please would you tell me, are Arrays necessary to use at all applications that written to do kind of function? – Basil Apr 06 '14 at 19:04
  • Sorry for that, i wanted to say that, when can i use arrays? and what is kind of applications need for arrays when it written in java? – Basil Apr 06 '14 at 20:29