Two Dimensional Array

September 11th, 2006 Admin Posted in Arrays No Comments »

A multidimensional arrays are arrays of arrays. We can declare a two dimensional array as follows

int [][] a;
or
int a[][];

In Java it is no needed that to declare the memory at the time of declaration. We can specify only one dimension at the time of allocation and the second dimension can be allocated manually

Example:

int a[][]=new int[3][];
a[0]=new int [3];
a[1]=new int [3];
a[2]=new int [3];

We can also allocate memory for the second dimension as per our requirement like

int a[][]= new int[3][];
int a[0] = new int[1];
int a[1] = new int[3];
int a[2] = new int[2];
this kind of array is used when it is sparsely populated.

AddThis Social Bookmark Button

One dimensional array

September 11th, 2006 Admin Posted in Arrays No Comments »

One dimensional array

Arrays can be declared in two ways:

a) data-type[] variable;

b) data-type variable[]

Declaration of variable does not mean that the memory is allocated for that array. It works only as a reference variable. In java memory will be  allocated with the keyword new.

Until or unless the actual memory is allocated for that array, we cannot be able to store the values within it.

To allocate memory for an array variable we have to write a statement as follows.

Variable = new data-type[size];

Even if we try to assign a value to the reference  variable “variable not initialized” error occurs.

As and then memory is allocated for array variable JVM creates an attribute called length for that variable. This attribute gives the size of that array.

Look at the following allocations

int[] m=new int[5]; is valid
int[] x,y=new int[5]; is not valid
int[] x,y;
x = new int[5];
y=new int[5];    is a valid allocation

We can also declare array for objects of our own class.

MyClass mc[] = new MyClass[5];

which declares 5 objects of MyClass.

AddThis Social Bookmark Button

What is an array?

September 11th, 2006 Admin Posted in Arrays No Comments »

  • An array is a collection of values of similar data types.
  • Arrays are also called as fixed length data structure.
  • Arrays can be declared for any data-type and for many dimensions.
AddThis Social Bookmark Button