wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes array assignments Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "array assignments" Watch "array assignments" New topic
Author

array assignments

harsha soma
Greenhorn

Joined: Nov 09, 2003
Posts: 7
Hello all,
The following code is compiling successfully.

public class arraryTest
{
public static void main(String[] args)
{
short[][] b = new short[4][4];
short[][][][] b2 = new short[2][3][2][2];
b2[1][1] = b;
}
}

My assumption is, any element b[x][y], where x is in (0,1) and y is in (0,1,2), should be a two dimensional array of size 2x2.

But short array b is a two dimensional array of size 4x4.

Shouldn't the compilation fail?
This is very counter-intuitive to me. When I run this program this does not throw any run-time exception either.
I greatly appreciate any correct reasons for this.
harsha soma
Greenhorn

Joined: Nov 09, 2003
Posts: 7
Correction in the above question, I meant any element b2[x][y], instead of b[x][y].
Thank you
Tim West
Ranch Hand

Joined: Mar 15, 2004
Posts: 539
Multidimensional arrays are constructed as "arrays of arrays". So, when you have int[][] myArr = new int[2][2];, "myArr", is a one dimensional array, but each element is itself an array. So, it seems like myArr is two dimensional.

Because myArr is just an array, it behaves the same as any array - each element must be of the correct type. This means you can assign any int[] to an element of myArr. Eg, you could do "myArr[1] = new int[50];". Assignment between array types, as you point out, doesn't do any length checking.

The initialisation code "new int[2][2]" creates an initial 'matrix' of size 2x2, but there is no restriction that myArr must always reference a 'matrix' of this size.

Cheers,


-Tim
 
jQuery in Action, 2nd edition
 
subject: array assignments
 
Similar Threads
Sierra and Bates Master Exam Question Question
Arrays
Master Exam Array question
Multi-dim Array
Multi dimansional Array,Master Exam