• Post Reply Bookmark Topic Watch Topic
  • New Topic

Uninitialized array access : one vs multi dimension  RSS feed

 
Ek Chotechawanwong
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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[0] = " + a[0]);
^
1 error

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
at ArrayTest.main(ArrayTest.java:4)

Question
Could you please explain why the behaviour is different?
Thanks so much in advance.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ekc,
Welcome to JavaRanch!
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.
Thanks Pardner! Hope to see you 'round the Ranch!
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the second one, you did initialize the array (a).

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.
 
Ek Chotechawanwong
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jeanne,
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?
Thanks,
Ek
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!