2

I was creating String array with few elements. At that time I notice that I have put comma after first element and it’s still compile. I thought it won’t compile. Then I print the size and it says 1

  String args [] = {request.getParentMessageID() , };
  System.out.println(args.length);

So

String args [] = {request.getParentMessageID() , };  and String args [] = {request.getParentMessageID()};

both behave as same.

Could someone kindly explain why these are not different and Why it compile.

someone
  • 6,577
  • 7
  • 37
  • 60
  • 1
    Please refer this answer http://stackoverflow.com/questions/3850203/java-array-initialization-list-ending-with-a-comma –  Nov 07 '12 at 06:52

2 Answers2

5

Trailing comma in a array initialization like that are ignored by compiler. Those are generally added so that later on adding something to the array, just requires adding the element without worrying about comma.

So it is allowed and is a valid syntax. This is also listed in JLS - Section#10.6 (Array Initializers): -

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

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
3

As per Java Language Specification 10.6

An array initializer is written as a comma-separated list of expressions, enclosed by braces { and }.

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

I hope you are clear now.

kosa
  • 65,990
  • 13
  • 130
  • 167