Arrays with trailing commas inside an array initializer in Java

Array initializers can be used to initialize arrays at compile-time. An initializer with trailing commas as shown below compiles fine.

int a[][] = {{1,2,} ,{3,4,} , {5,6,},}; //Trailing commas cause no compiler error

for(int i=0;i<a.length;i++)
{
    for(int j=0;j<2;j++)
    {
        System.out.print(a[i][j]+"\t");
    }
    System.out.println();
}

Output :

1        2        
3        4        
5        6     

Also legal with one dimension arrays as obvious with the above discussion.

int[] b = {1, 2, 3, 4, 5, 6,}; //A trailing comma causes no compiler error

for(int i=0;i<b.length;i++)
{
    System.out.print(b[i]+"\t");
}

Output :

1        2        3        4        5        6

Even the following is a legal syntax and compiles fine.

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

The compiler should expect a constant value (or another initializer) after and before a comma ,. How is this compiled? Does the compiler simply ignore such commas or something else happens in such a scenario?


The trailing comma is ignored. From the Java specification:

A trailing comma may appear after the last expression in an array initializer and is ignored.