Previous | Home | Next |
Array is a collection of same type of element. It is a data structure where we store similar elements. An array in java is an ordered collection of the similar types of variable . Java allows array of any dimension. An array in java is a bit different from c or c++. We can not specify the size of the array at time of declaration. The memory allocation is always dynamic. Every array in java is treated as an object with one special attribute, which specify the number of elements in the array. .to declare an array write a data type followed by [] followed by the identifier.
Array in java is index based, first element of the array is stored at 0 index.
There are two types of array.
- Single/One Dimensional Array
- Multidimensional Array
Syntax :
type array-name[]; // no memory allocation takes place in declaration or type []array-name;
Where type defines the data type of array element like int, double etc.
array-name is the name of array.
Note: That declaration does not actually create an array. it only declares a reference.
In java, initialize an array can be done by using new keyword.
Syntax :
array-name=new type[Size] //Size must be a constant or a variable
Note:All the elements of array will be automatically initialized to zero.
Array index start with zero.
int a[]; a= new int[5]; or int a[]=new int[5];
Example :
int a[], b,c;//a is reference variable b and c is not an array reference variable a=new int[5]; //is valid b=new int[5];//is not valid c=new int[5];//is not valid OR int a[],b[],c[];// a,b and is reference variable a=new int[5];//is valid b=new int[5];//is valid c=new int[5];//is valid OR int [],a,b,c;//a,b and is refernce variable a=new int[5];//is valid b=new int[5];//is valid c=new int[5];//is valid OR int [],a,b,c; a=b=c=new int[5];//is not valid OR int a[]={10,20,30,40,50};
Previous | Home | Next |