I have a basic language question about array access. There seems to be difference in how java compiler handle uninitilized member between one and multi dimensional array. (I use Sun - j2sdk 1.4.2_03 on Win2k).
In the one dimension array,
In this case I cannot compile the program.
ArrayTest.java:4: variable a might not have been initialized
System.out.println("a = " + a);
However, in case of 2 dimensional array, I can compile but I got runtime exception (NullpointerException).
In this case I can run the program but got NullPointerException.
Exception in thread "main" java.lang.NullPointerException
Could you please explain why the behaviour is different?
Thanks so much in advance.
It is a valid case to have an array that contains all null elements. For example, you may want to populate it later. So the compiler doesn't know for sure whether the array has been initialized.
In the first example, the array was not initialized at all. This is a case that the compiler can identify.
I think just allocates the first dimension aka. array of 2 int elements however it doesn't explicitly construct the second dimension of each - it doesn't say how many int elements will be in each int array.
Therefore, it's the same as the first case to me.
If it's a kind of java compiler limitation/design issue, I would be OK with the difference. But I am afraid, I am missing something on language concept.
In other words, I see that javac can check whether one dimensional array is initilized or not. Is there any reason why java compiler doesn't check the subsequent dimension of the multi-dimensional array?