Java: Arrays
What is an array?
An array is a very common type of data structure.
- All of the elements sored in the array must be of the same data type.
- Once defined, the size of an array is fixed and cannot increase to accommodate more elements.
- The first element of an array starts with zero.
Instead of entering each piece of data separately:
x0=0;
x1=1;
x2=2;
x3=3;
x4=4; etc.
the array x[] will hold data in this way:
x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4; etc
The index (the number in the bracket[]) can be referenced by a
variable for easy looping.
for(count=0; count<5; count++) {
System.out.println(x[count]);
} |
Using an array
To use an array in a program you have to complete all of the following steps:
The syntax for declaring array variables:
<elementType>[] <arrayName>;
or
<elementType> <arrayName>[];
-----------------------------------------------------
Example that defines that intArray is an ARRAY variable of which will store integer values:
int intArray[];
OR
int []intArray;
|
The syntax for constructing an Array:
<arrayName> = new <elementType>[<noOfElements>];
------------------------------------------------------
Example that intArray will store 10 integer values:
intArray = new int[10]; |
The syntax for 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 |
You can combine steps:
- Syntax for declaration and construction combined:
int intArray[] = new int[10];
|
- Syntax for declaring and initializing an array
<elementType>[] <arayName> = {<arrayInitializerCode>};
Example that initilializes an integer array of length 4 where the first element is 1 , second element is 2 etc.
int intArray[] = {1, 2, 3, 4}; |
Multidimensional arrays
Multidimensional arrays, are arrays of arrays.
To declare and construct a multidimensional array variable you need to specify each additional index using another set of square brackets.
For example:
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.
For example:
int twoD[][] = new int[4][];
We have four set for the first array (0,1,2,3) - each of those can then be set as housing different numbers of data elements.
twoD[0] = new int[5];
twoD[1] = new int[6];
twoD[2] = new int[7];
twoD[3] = new int[8];
An array of Objects
It is possible to declare array of reference variables.
Syntax:
Class <array_name> = new Class[array_length] |
This page extracted facts about arrays from a Java tutorial hub.com tutorial. I suggest you take a look at this site. It is a free educational site.