Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Initialization using { } in Java

Tags:

java

arrays

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.

like image 880
Kazekage Gaara Avatar asked Jul 13 '12 15:07

Kazekage Gaara


1 Answers

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:

  • Java array initialization list ending with a comma
  • History of trailing comma in programming language grammars
like image 123
aioobe Avatar answered Oct 04 '22 00:10

aioobe