Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays with trailing commas inside an array initializer in Java

Tags:

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?

like image 663
Tiny Avatar asked Jul 23 '12 23:07

Tiny


People also ask

Can trailing commas be used in objects and arrays?

JavaScript has allowed trailing commas in array literals since the beginning, and later added them to object literals, and more recently, to function parameters and to named imports and named exports. JSON, however, disallows trailing commas.

How arrays can be initialized in Java?

Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.

How do you initialize an array of arrays?

To initialize an array of arrays, you can use new keyword with the size specified for the number of arrays inside the outer array. int[][] numbers = new int[3][]; specifies that numbers is an array of arrays that store integers.

How do you initialize a filled array in Java?

Solution. This example fill (initialize all the elements of the array in one short) an array by using Array. fill(arrayname,value) method and Array. fill(arrayname, starting index, ending index, value) method of Java Util class.


1 Answers

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.

like image 164
Mark Byers Avatar answered Oct 13 '22 17:10

Mark Byers