Sunday 31 March 2013

Arrays in JAVA

Leave a Comment
An array is a very common type of data structure where in all elements must be of the same data type.Once defined , the size of an array is fixed and cannot increase to accommodate more elements.

x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;
Using and array in your program is a 3 step process -
1) Declaring your Array
2) Constructing your Array
3) Initializing your Array Syntax for Declaring Array Variables is
int intArray[];
 // Defines that intArray is an ARRAY variable which will store integer values
int []intArray;

Constructing an Array
intArray = new int[10]; // Defines that intArray will store 10 integer values
Declaration and Construction combined
int intArray[] = new int[10];
Initializing an Array
intArray[0]=1; // Assigns an integer value 1 to the first element 0 of the array
 
intArray[1]=2; // Assigns an integer value 2 to the second element 1 of the array

Declaring and Initializing an Array
int intArray[] = {1, 2, 3, 4};
// Initilializes an integer array of length 4 where the first element is 1 , second element is 2 and so on.


Multidimensional Array To declare a multidimensional array variable, specify each additional index using another set of square brackets.
int twoD[ ][ ] = new int[4][5] ;


When you allocate memory for a multidimensional array, you need only specify the memory for the first (leftmost) dimension. You can allocate the remaining dimensions separately. In Java the length of each array in a multidimensional array is under your control.
int twoD[][] = new int[4][];
 
twoD[0] = new int[5];
 
twoD[1] = new int[6];
 
twoD[2] = new int[7];
 
twoD[3] = new int[8];



0 comments:

Post a Comment