15

We can initialize an array like this:

int myArray[][] = { {10,20} ,{30,40} , {50} };

It works fine.

But I came across a peculiar situation.

int myAnotherArray[][] = { {,} ,{,} , {,} };

The above line of code compiles fine. This according to me is weird. Because when the compiler would parse this statement , it would encounter { and , and } all together. Shouldn't the compiler be expecting a constant or a literal in between ? I would appreciate it if someone would tell me how exactly the above statement is parsed and what exactly the compiler does when it encounters such a situation.

Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
  • 6
    @Mong134 this doesn't seem to help. – Denys Séguret Jul 13 '12 at 15:44
  • 2
    Take a look at [this question](http://stackoverflow.com/questions/3758490/net-now-support-trailing-comma-in-array-like-python-does). It's about .NET, but Java does the same thing, because it borrowed it from the same language (I mean "C", of course, where the questionable practice of allowing trailing commas has originated). – Sergey Kalinichenko Jul 13 '12 at 15:47

1 Answers1

23

This is simply a quirk of the fact that the syntax allows for trailing commas.

Allowing trailing commas is for instance kind to code generators generating things such as { 0, 1, } and allows you to for instance conveniently comment out the last row in

int[] myArray = {
    0,
//  1
};

(As you may have figured out, trailing , is ignored, i.e. { , } yields an empty array.)

Related questions:

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 4
    +1 Exactly. If you looked at the contents of the array, you would see all the subarrays are empty (demo: http://ideone.com/Pvg0G). C# works the same way. – mellamokb Jul 13 '12 at 15:43