Definition of One Dimensional Array
One dimensional array is a list of variables of same type that are accessed by a common name. An individual variable in the array is called an array element. Arrays forms a way to handle groups of related data.
Syntax of Multi dimensional Arrays
To create an array, you need to perform two steps :
1) Declare the array :
To declare an array below is a general form or syntax.
type varName[];
Where type is valid data type in java and varName is a name of an array.
Example : int iarr[];
2) Allocate space for its elements :
To allocate space for an array element use below general form or syntax.
varName = new type[size];
Where varName is the name of the array and type is a valid java type and size specifies the number of elements in the array.
Example : iarr = new int[10];
Above statement will create an integer of an array with ten elements that can by accessed by iarr.
Structure of one dimensional array
iarr[0] |
iarr[1] |
iarr[2] |
iarr[3] |
iarr[4] |
iarr[5] |
iarr[6] |
iarr[7] |
iarr[8] |
iarr[9] |
Note that array indexes begins with zero. That means if you want to access 1st element of an array use zero as an index. To access 3rd element refer below example.
iarr[2] = 10; // it assigns value 10 to the third element of an array.
java also allows an abbreviated syntax to declare an array. General form or syntax of is is as shown below.
type varName[] = {v0, v1, v2 ........ v10};
Where varName is the name of the array and type is a valid data type and v0, v1 to v10 are the elements of an array. In this case new is not used and memory for the array is automatically provided.
Example : int iarr = {1,2,3,4,5,6,7,8,9,10};
Example of One dimensional array
Example : This example shows how to declare initialize and display an array.
// Declaration of allocating memory to an array
int iarr[] = new int[3];
// Initializing elements
iarr[0] = 1;
iarr[1] = 2;
iarr[2] = 3;
//Display array elements
System.out.println(iarr[0]);
System.out.println(iarr[1]);
System.out.println(iarr[2]);
// Or Use for loop to display elements
for (int i = 0; i < iarr.length; i = i + 1)
{
System.out.print(iarr[i]);
System.out.print(" ");
}