Declaring and Creating 2-D arrays in Java:  3 seperable steps

Suppose MyClass is a Class.

MyClass a[][];                 Declares  a as an array.

                               Does not  create the array.


a[i][j] = new MyClass[M][N];   Creates M†¥N array;

                               Does not  create the objects.

a[i][j] for i < M, j < N

  will be null.


a[i][j] = new MyClass();       creates a[i][j]


Putting all together:

MyClass a[][] = new MyClass[M][N];

for(int i=0; i < M ; i++)

  for(int j=0; j < N; j++)

    a[i][j] = new MyClass( );

Note :  If elements are primitive type rather than objects, the 3rd step is not used.

 

To Next Slide To Previous Slide To Contents