• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

missing dimension

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
That's my roommate. He's kinda weird, but he always pays his half of the rent. And he gave me this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic