Thursday 10 November 2016

ARRAY


  
   Array is a group of contiguous or related data items that share a commonname.
   One Dimensional Array:
o   A list of items can be given one variable name using only one subscript and such a variable is called a single-subscripted variable or a one-dimensional array.
o   Creation of array involves three steps:
a)    Declaring the array: In Java array may be declared in two forms:
type arrayname[];
type [] arrayname;
Ex:   int num1[];
         float[] num2;
        
b)    Creationof Array: After declaring an array, we need to create it in the memory. In Java new operator is used to create an array:
arrayname=new type[size];
Ex:  num1=new int[5];
         num2=new float[10];
The above two steps can be combined into single step as follows:
         int num=new int[5]; 
c)     Initialization of Arrays:There are various ways to initialize an array:
Arrayname[subscript]=value;
Ex:num[0]=10;
         num[1]=20;
It is also possible to initialize an array at the time of declaration:
type  arrayname[]={list of values};
Ex: int num[]={10,20,30,40};
It is also possible to assign an array object to another:
int a[]={10,20,30};
int b[];
b=a;
Loops can also be used to initialize an array:
int num[50];
for(int i=0;i<50;i++)
     num[i]=0;
d)    Array Length:In Java length is used to calculate the length of an array:
Ex: int size=num.length;
Usefulwhen the size of array is not known.
   Two Dimensional Array:
o   Declaring 2D array:int num[][];
o   Creating memory for 2D array:num=new int[3][4];
int num[][]=new int[3][4];
o   Initializing 2D array:
int num[2][3]={0,0,0,1,1,1};
int num[2][3]={{0,0,0},{1,1,1}};
int num[2][3]={
{0,0,0},
{1,1,1}
      };
o   Accessing Values: Values from 2D array can be accessed using subscript or index value:
int val=num[1][2];
    Variable Size Array:
o   Java treats multidimensional array as “arrays of arrays”. It is possible to declare a two dimensional array as follows:
int x[][]=new int[3][];
x[0]=new int[2];
x[1]=new int[4];
x[2]=new int[3];
o   Each row of the array x have different length.

No comments:
Write comments