Thursday, 9 July 2009

Arrays

  • Arrays are a collection of like typed variables referenced by a common name.
  • Each element in an Array is referenced by a index.
  • Index starts from 0 , that is first element is stored at index 0
  • Arrays can be multi dimensional
Declaration
It is declared like other data types but with [] .
int arr1 [] ; // single dimension array
int arr2 [][] // two dimension array
int arr3 [][][] // three dimension array
Here int (could be any valid data type) specifies that this array can hold int values
Initialization
There are different ways to initialize an array
Using new operator
float arr1 [] = new float [5] ;
new operator dynamically allocates memory at runtime
Here 5 is the size of array, number of elements it can hold
Now each element can be accessed by it's index and assigned a value
Note: Compiler provides default value (depending on data type) to each
element.
arr1 [0] = 10 ;
arr1 [3] = 20 ;
and so on
Don't go beyond index 4, because that is the last index.
It will result in ArrayIndexOutOfBoundsException

Curley braces style
float arr1 [] = {5.0 , 3 , 4 } ;
Values are given as comma seperated list enclosed in { }
here, size need not be specified as it is same as the number of
values given in the list

Multi dimensional arrays
Two Dimensional
You can think of it as a row column matrix
double twoDim [] [] = new double [dim1] [dim2] ;
dim1 : rows in the matrix
dim2 : columns in the matrix
int a [] [] = new int [3] [3]
a00 a01 a02
a10 a11 a12
a20 a21 a22
Remember, both the indexes start at 0
int a [] [] same as int [] a [] same as int [] [] a