An array is indexed
collection of homogeneous elements.
v For
storing the similar data type. With single variable name
v Once
the array is created it is not possible for increase or decrease the size based
on the requirement
v Arrays
shows wonderful performance compared to collections
Creating an array:
Syntax:
{data type}[] identifier=new {data type}[index];
Ex: int[] i=new int[10];
int[][] j=new int[2][3]; //multi-dimensional
array
int[][][] k=new int[2][3][2]; //multi-dimensional
array
Memory allocation for[2][3] Array:
Array creation having two steps:
Step 1: Declaration
This declaration is specifies the
dimension of an array
Example:
Important point: At the time of array declaration we are not allowed to specify the
size. int [] a; (or)
int a[];
Step 2: Construction
At the time of array construction we
should specify the size
Example:
int [] a=new int[10];
Important points:
1. It
is legal to have array size is zero
2. We
are not supposed to give –ve value as array size. It won’t create any
compilation error. But it gives runtime error
3. Arrays
always expect integral values as a size. It will allow int, byte, short, char
4. For
knowing the size of array we will use ‘length’ property
Array example:
class ArrayDemo
{
public static void
main(String[] args)
{
int []a=new int[10];
//knowing
the size of an array
System.out.println("size
of array a: "+ a.length);
//inserting
values
for(int i=0;i<10;i++){
a[i]=i;
System.out.println("Value
inserted "+"a["+i+"]");
}
// reading the values from array
for(int j=0;j<10;j++){
System.out.println("value of
a["+j+"] index is:"+a[j]);
}
}// end of main method
}//end of
class
Output:
size of array a: 10
Value inserted a[0]
Value inserted a[1]
Value inserted a[2]
Value inserted a[3]
Value inserted a[4]
Value inserted a[5]
Value inserted a[6]
Value inserted a[7]
Value inserted a[8]
Value inserted a[9]
value of a[0] index
is:0
value of a[1] index
is:1
value of a[2] index
is:2
value of a[3] index
is:3
value of a[4] index
is:4
value of a[5] index
is:5
value of a[6] index
is:6
value of a[7] index
is:7
value of a[8] index
is:8
value of a[9] index
is:9
No comments:
Post a Comment