Showing posts with label arrays. Show all posts
Showing posts with label arrays. Show all posts

Thursday, February 10, 2011

Array Declarations

Java has two ways in which one can declare an array, one which is backwards compatible with the notation used in C & C++ and another which is generally accepted as being clearer to read, C# uses only the latter array declaration syntax.
C# Code

int[] iArray = new int[100]; //valid, iArray is an object of type int[]
float fArray[] = new float[100]; //ERROR: Won't compile

Java Code

int[] iArray = new int[100]; //valid, iArray is an object of type int[]
float fArray[] = new float[100]; //valid, but isn't clear that fArray is an object of type float[]

Arrays Can Be Jagged

In languages like C and C++, each subarray of a multidimensional array must have the same dimensions. In Java and C# arrays do not have to be uniform because jagged arrays can be created as one-dimensional arrays of arrays. In a jagged array the contents of the array are arrays which may hold instances of a type or references to other arrays. For this reason the rows and columns in a jagged array need not have uniform length as can be seen from the following code snippet:
 int [][]myArray = new int[2][]; 
myArray[0] = new int[3];
myArray[1] = new int[9];
The above code snippet is valid for both C# and Java.