• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

missing dimension

 
jaspreet atwal
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried to compile the below code and i get "array dimension missing" error

But if I compile the following code, it gets compiled. Anyone please explain why don't i get missing dimension error this time?

 
Sergio Calvo
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's because the way in which arrays work in Java.

The Java compiler always, always needs to know how much space to take for your Array when you are creating it (with "new").

In the first case, int[] arr = new int[];

The compiler doesn't have that data, so it will always, always, fail. It doesn't know how much space do you actually need.

But, in the second case, there's a subtle difference,

int[][] arr = new int[5][];

The compiler actually has the data it needs, it needs 5 spaces for the new array (the first dimension). That's all it needs.

The second dimension doesn't matter at this point since it is another set of different arrays. So the compiler will happily continue with no problems.

But, you will actually need to make that initialization when you try to use it, say for example:


arr[0] = new int [2]; //arr[0] is going to be another array with two ints.

arr[0][0] = 50; //the first int in array[0] is 50;
arr[0][1] = 100; //the second int in array[0] is 100;

Does it makes sense?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic