Array is a
collection of same data type variables under one name. Array can be available
in following types.
·
One
dimensional array
·
Two
dimensional array
·
Three or
more dimensional array
Ex: int
mark[]=new int[5];
Size 5
Lowerbound 0
Upperbound 4
Element mark[0],mark[1],….mark[4]
Array Name mark
Subscript 0,1,2,3,4
Array Declaration
One
dimensional array
Type 1
datatype
variablename[]=new datatype[size];
int n[]=new
int[10];
Type 2
datatype[]
variablename=new datatype[size];
int[] n=new
int[10];
Type 3
datatype
variablename[]={value….};
int
n[]={1,2,3,4};
String
name[]={“java”,”j2ee”};
char
ch[]={‘a’,’b’,’c’};
Type 4
datatype
variablename[]; // step 1
variablename=new
datatype[size]; //step 2
int n[];
n=new int[5];
In type 4 the
array can be declared as class scope, then it can be resized within method at
more times.
Two
dimensional array
Type 1
datatype variablename[][]=new
datatype[rowsize][columnsize];
Ex: int
a[][]=new int[2][3]; // a has 6 elements (2*3)
Type 2
datatype
variablename[][];
variablename=new
datatype[rowsize][coulmnsize];
int b[][];
b=new int[2][3];
Type 3
datatype
variablename[][]={{values},{values}};
int
a[][]={{1,2,3},{1,2,3}};
Three
dimensional array
Type 1
int a[][][]=new
int[2][2][2];
Type 2
int a[][][];
a=new int[2][2][2];
Four
dimensional array
Type 1
int
a[][][][]=new int[2][2][2][3];
Type 2
int a[][][][];
a=new
int[2][2][2][3];
Jagged
arrays
Two or more dimensional can be declared as jagged arrays to allocate
memory at run time.
Runtime
memory allocation
Ex 1
int a[][]=new
int[5][];
a[0]=new int[3];
a[1]=new
int[10];
It means a[0]
has 3 columns, a[1] has 10 columns.
Ex 2
int a[][][]=new
int[2][][];
a[0]=new
int[2][3];
a[1]=new
int[3][4];
It means a[0]
has 2*3 array, a[1] has 3*4 array
Assigning arrays
Arrays can be assigned in java. Consider following syntaxes.
Ex 1
int a[]=new int[2];
int b=a[0]; // One value assign
Ex 2
int a[][]=new int[2][2];
int b[]=a[0]; // One dim assign
int c[]=a[1]; // One dim assign
Ex 3
int a[][][]=new int[2][2][3];
int b[][][]=a; // Three dim assign
int c[][]=a[0]; // Two dim assign
int d[]=a[0][0]; // One dim assign
Ex 4
int a[][][][]=new int[2][2][2][2] ;
int b[][]=a[0][0]; // Two dim assign
int c[][][]=a[0]; // Three dim assign
int d[][][][]=a;// Four dim assign
No comments:
Post a Comment
Note: only a member of this blog may post a comment.