Array:
A collection of data items, all of the same type, in which each item's position is uniquely designated by an integer.
SINGLE DIMINSION ARRAY:
Declaring an Array :
int [ ] world;
int world [ ];
This is the syntax of declaring an integer array variable, No memory is allocated to hold the array itself at this point.
Defining an Array:
int [ ] world = new int [5];
int world [ ] = new int [5];
Initializing an Array :
int [ ] world = new int [5];
world[0]=4;
world[1]=2;
int [ ] world = {4,2,6,8,5};
This statement will create an array with the size of 5 elements & will store the values which are give between the braces.
int [ ] world = new int [ ] {1,2,3,4,5};
here is another way of initializing an array.
Example:
public class world {
public static void main (String [] args){
int [] a = new int[10];
System.out.println(a);
a[0]=10;
a[1]=20;
a[2]=30;
System.out.println(a[1]);
System.out.println(a[4]);
System.out.println(a[12]);
}
}
Result :
[1@73d6a5 // address at a
20 // value at a[1]
0 // at a[4] we have not initialized any value so by default 0 will be placed here.
Array index out of bounds Exception. // cause a[12] is not the element of a
By default java assigns 0 to the variable data type of BYTE, SHORT, LONG, & INT, 0.0 to FLOAT, & DOUBLE, false to BOOLEAN & '\u0000' (Unicode of zero) to CHAR.
Example:
public class world {
public static void main (String [] args){
int [] a = new int[10];
for(int i=0; i<10;i++){
a[i]=i+1;}
for(int i=0;i<10;i++){
System.out.println(a[i]);
}
}
}
With the help of loops we can initialize any array very easily.
Reusing Array Variables:
int [ ] world = new int [10]; // this statement will create an array of 10 elements in your program
Now if the need of program changes & you want the same array with 50 elements, then you can reuse the array variables, you would simply write:
world = new int [50];
From this process the previous values would be discarded.
DOUBLE DIMINSION ARRAY:
Declaring & initializing 2-D array:
int [ ] [ ] a = new int [10] [100];
int [ ] [ ] b = {{1,2,3,4,5},{1,2,3,4,5}};
Example:
public class world {
public static void main (String [ ] args) {
int [ ] [ ] a = new int [(int)(Math.random()*10)][(int)(Math.random()*10)];
for(int i=0;i<a.length;i++)>
for(int j=0;j<a[i].length;j++)>
{ a[i][j]=i+j+1;
}
for(int i=0;i<a.length;i++)>
for(int j=0;j<a[i].length;j++)>
{System.out.println(a[i][j]);
}
}
}