Accepted answer

why should i insert a trailing comma?

you don't need to. i suspect sonar should just be showing a warning there.

it depends on programmer's preference what he prefer. adding a trailing comma at the end of the array, makes it easy to remove or add any entry later on from the array.

so, if you have an array like:

string[] arr = new string[] {

adding an entry merely requires you to add that entry with trailing comma at the end of your array. without comma, you would first need to add a comma, then the element.

and removing an element just requires you to remove that line containing that element. or just commenting out that line.

string[] arr = new string[] {
              //  "ghi",    // this won't cause any error

if trailing comma wasn't allowed, then if you remove the last element, you would have to go and remove the comma before it too. well, i know this reason is quite absurd. but that's just allowed.

this is highly beneficial for code generators while generating the code for array initialization. they can simply go on adding elements with trailing comma in the array, without worrying about whether it's the last element.

let's take an example:

stringbuilder array = new stringbuilder();

array.append("int[] arr = new int[] {").append("\n");
for (int i = 0; i < 10; ++i) {
    array.append(i + ",").append("\n");

consider if a trailing comma wasn't allowed, then how that code would look like. you would have to handle the last element separately. so, it's just doing good to the code generators.


jls (ยง10.6) states:

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

it is in no way necessary.

however, it's somewhat of a style choice, and it can make things easier for reordering, manipulating, and/or copy-pasting of the last element. moving requiredpermissions.api_password_recover to another place or pasting in new entries below it can be easier as you don't need to add an extra comma and risk a syntax error from mistypes or misclicks.

Related Query

More Query from same tag