Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array initialization list ending with a comma

Tags:

java

c

syntax

The comma , items separator used in an array initialization list may end the list in C, this is mentioned in The C Programming Language 2nd ed by Kernighan & Ritchie .

e.g.

  int c[] = { 1, 2, 3, };

This is convenient when the list is long, and one doesn't want to have to change/check the previous line when adding items

  long long c[] = { 
                    22342342344,
                     4324234234,
                    12312311111,
                   };

However in Java I could observe two different behaviors:
In Eclipse, the ending , is accepted while some versions of the maven compiler plugin complain and throw a compilation error.

However, I didn't find any mention of this singularity in the Flanagan's Java book.

What is the official rule regarding an ending comma after the initialization items?
Is it recommended not to use it?

like image 516
Déjà vu Avatar asked Oct 03 '10 14:10

Déjà vu


People also ask

Does Java support trailing commas?

JavaScript allows trailing commas wherever a comma-separated list of values is accepted and more values may be expected after the last item. This includes: Array literals.

What is the correct syntax for initializing an array?

To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.

How do you initialize an entire array in Java?

We can declare and initialize arrays in Java by using a new operator with an array initializer. Here's the syntax: Type[] arr = new Type[] { comma separated values }; For example, the following code creates a primitive integer array of size 5 using a new operator and array initializer.

Are arrays in Java automatically initialized?

In Java, all array elements are automatically initialized to the default value.


1 Answers

Section 10.6 of the spec explicitly says that a trailing comma is allowed (and ignored):

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

Link

like image 192
Pointy Avatar answered Oct 14 '22 05:10

Pointy