Sunday 29 January 2012

Arrays in Java


Introduction:
•An array is a collection of same type variables referenced by a common name.
•All the elements in the array are of the same data type.
•Elements of an array are accessed individually using the index.
•The index value in every array starts with 0 (zero).
•An array can have one or more dimensions.

Creating Arrays:
•Creation of arrays is a two step process:
1) Declaring an array variable.
2) Allocating memory for the array.

•Syntax for declaring an array variable is:

type array-name[];

type – Data type of the array.
array-name is any valid identifier.


•Syntax for allocating memory for an array:

array-name = new type[size];

new – keyword used to allocate memory for the array.
size – No of elements that the array will hold.

•We can combine both the steps into a single one as shown below:
type array-name[] = new type[size];

Example:
int a[] = new int[20];

a – name of the array.
int – data type of the elements in the array.
new - for allocating memory to the array.
20 – array ‘a’ can hold 20 integer elements/values.



•Another way of creating the arrays:

type[] array-name = new type[size];

Example:
int[] a = new int[20];

This syntax is useful when declaring multiple arrays of same type:
int[] a1,a2,a3,a4,a5;

Initializing array elements:
•Every array element is accessed using its index value.
•Syntax for initializing the array elements is:

array-name[index] = value;

Example:
int a[] = new int[3];
a[0] = 10;
a[1] = 20;
a[2] = 30;


•There is another way for initializing array elements, right at the time of declaring the array.

Example:
int a[] = {1,2,3,4,5};

In the above example, ‘a’ is an integer type array with size automatically set to 5. All the 5 elements are initialized with the values 1,2,3,4,5.
a[0] is 1, a[1] is 2, a[2] is 3, a[3] is 4 and a[4] is 5.

Multidimensional Arrays:
•Until now we have only seen one-dimensional array. But, an array in general can have more than one dimension.
•Let’s see about two-dimensional arrays. For each dimension, we must specify an extra set of [].
•A two dimensional array is declared as shown below:

int a[][] = new int[3][4];
‘a’ is a two dimensional array which can hold 12 elements in 3 rows and 4 columns.


•Initializing two dimensional array elements is done using the index values:
int a[][] = new int[2][2];
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;

Two - Dimensional array representation

No comments:

Post a Comment