An array is a group of similar-typed variable that are referred by a common name. A specific element in an array is accessed by its index. An array may have one or more dimensions.
One Dimensional Arrays:
The general form of a one dimensional array declaration is as:
type variable-name[];
Note:
- Here type declares the base type of array like as int , char, boolean etc.
For example: int month_days[];
- Although this declaration establishes the fact that month_days is an array variable, no array actually exists. And value of the month_days is set to NULL, which represents an array with no value.
- To link month_days with an actual physical array of integers, you must to allocate using new keyword and assign it to the month_days.
- new is a special operator, which is used for memory allocation. The syntax for this as:
array-variable name = new type[size];
here type specifies the type of the array and size specifies the number of elements in the array.
For example: suppose we want to allocate a 12 -element array of integers.
int year_months = new int[12];
Example for 1-D array:
class OneDArray{
public static void main(String ar[]){
int year_months = new int[12];
year_months[0]=1;
year_months[1]=2;
year_months[2]=3;
year_months[3]=4;
year_months[4]=5;
year_months[5]=6;
year_months[6]=7;
year_months[7]=8;
year_months[8]=9;
year_months[9]=10;
year_months[10]=11;
year_months[11]=12;
System.out.println(year_months[5]); //it prints the 5th index value
}
}
output: 6
Multidimensional Arrays:
The Multidimensional arrays are actually arrays of arrays.To declare multidimensional array variable,specify each additional index using another set of square brackets. For example, we want to declare 2 dimensional Array.
int twoD =new int[4][5];
this allocates a 4 by 5 array and assign it to twoD;
Example for multidimensional array:
Class TwoDArray{
public static void main(String a[]){
int two = new int[4][5];
int k=0;
for(int i=0;i<4;i++){
for(int j=0;j<5;j++){
two[i][j]=k;
k++;
}
}
for(int i=0;i<4;i++){
for(int j=0;j<5;j++){
System.out.println(two[i][j] + ” “); //print value at index of i and j
System.out.println();
}
}
}
}
output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19