CSC/ECE 517 Summer 2008/wiki1 6 c9)

From Expertiza_Wiki
Revision as of 04:01, 29 May 2008 by Abhuwan (talk | contribs)
Jump to navigation Jump to search

An array is an indexed collection of items of same data type.

Declaration of an array in Java:- We are not allowed to declare an array consist of multiple data type(like double and integer in same array). The array is declared as

integer [] employee; or double employee[];

The square brcaket indicates the array declaration. In Java array is an reference data type and memory is allocated to store the data in the array.The memory can be allocated with the

keyword "new".

employee = new integer [5];

It can alos be declared in one line as :-

integer employee = new integer [5];

Now the Employee array has allocated the memory to store the five integers.Unless we have initialised the array at the time of declaration we need to specify the size of an array before using it.

The indexing of an array starts from 0 to size-1.It means if the array is of size 5 then first element is stored at employee[0] and the last one is at employee[4] .In an array the elements can be initialised one by one upto the previously declared size of an array.

for ex:-

        String employee = new String [5]
       for(int i = 0; i <5 ; i++)
       {
         employee[i] = i;
       } 

If elements are initialised at the time of the declaration then ther is no need of specifying a size to an array.The size of an array is same as the number of initialised elements. for ex:-

String [] weekday = {Monday,Tuesday,wednesday,Thursday,friday,Saturday,Sunday};

In this example the size of an array is 7..