Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, October 21, 2010

Java vs C#: The Battle of ForEach-Loops

There have been instances in your programming life that you wanted to loop through an array or a collection for whatever reasons. Each language has its own way of getting through this. For some period of time C# has been conveniently providing a solution for this by providing the foreach code block. It works pretty simple, just provide an array or collection then provide a variable to store each element into then you'll be able to go through each element that easy:
int[] myArray = new int[] { 2, 3, 5, 7, 11, 13 };
foreach (int i in myArray) {
    System.Console.WriteLine(i);
}
In Java, however, it wasn't that easy. Before Java 1.5, to be able to go through each element of an array you will have to set an initial value, terminating test value, and then an increment statement:
int[] myArray = {2, 3, 5, 7, 11, 13};
for(int i=0; i<myArray.length; i++) {
    System.out.println(myArray[i]);
}
When Java realized that C# is gaining some edge they released Java 1.5 with all the collection classes and the enhancement of for loop to handle foreach activities. Now, looping through an array or collection can be done in Java just as easy as you do it in C#:
int[] myArray = {2, 3, 5, 7, 11, 13};
for(int i : myArray) {
    System.out.println(i);
}
Do take note, however, that this for-loop structure will not work on Java 1.4 and lower. And if you're using those versions of Java then you have to use the 1st Java code block that's presented here.

I hope that you learned something new today!