Wednesday, February 18, 2015

C# vs Java : for-each loops

In Java, the for-each loop looks like this
for(int i : array) {
In C#, the for-each loop looks like this:
foreach (int i in array) {

C# does not allow you to modify the iteration variable.
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};

foreach(int i in array) {
  i = 3; // compiler error
  // Cannot assign to 'i' because it is a 'foreach iteration variable'
}
Java, on the other hand, allows this.
public class Klass {
   public static void main(String... args) {
      int[] array = {1,2,3,4,5};

      for(int i : array) {
         System.out.print(i + " vs. ");
         i = 3;
         System.out.println(i);
      }
   }
}
The following output is what the above program produces.
1 vs. 3
2 vs. 3
3 vs. 3
4 vs. 3
5 vs. 3

C# allows you to use the for-each loop with multi-dimensional arrays.
public class Klass {
  public static void Main() {
    int[,] array = new int[2, 2] { 
      {1, 2},
      {3, 4}
    };

    foreach(int i in array) {
      System.Console.Write(i + " ");
    }

    System.Console.WriteLine();
  }
}
Here's what the above outputs
1 2 3 4
Unfortunately, Java doesn't support this type of array. It does, however, support jagged arrays. Here what the above program looks like in Java:
public class Klass {
   public static void main(String... args) {
      int[][] array = new int[2][];
      array[0] = new int[]{1, 2};
      array[1] = new int[]{3, 4};

      for(int[] i : array) {
         for(int j: i) {
            System.out.print(j + " ");
         }
         System.out.println();
      }
   }
}

See Also: Java Arrays
See Also: C# vs Java : arrays

No comments:

Post a Comment