wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Why Extra Comma is allowed when constructing an array? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why Extra Comma is allowed when constructing an array?" Watch "Why Extra Comma is allowed when constructing an array?" New topic
Author

Why Extra Comma is allowed when constructing an array?

Leon Omk
Ranch Hand

Joined: Aug 17, 2010
Posts: 75



Why do above 2 statements compile without even a warning?

Personally, I don't like these weired statements. Anyone can give me any reasonable excuses to help me accept them? Thanks in advance.


OK, so that other guy knows Java better than I do, but I bet he can't speak Wuhanese(a Chinese Dialect) like me.
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

What do you all have with that extra comma today ?

[My Blog]
All roads lead to JavaRanch
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

I can imagine one reason : when you want to allow the array to grow in further version of your code, without touching the previous version. For example :

You know this array of product may change in the future. You can add a new product, without having to take care of the last one. If the code looked like this :

you'd have to add an extra comma.
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

Of course, you could also have

, but personnally, I prefer to have trailing commas
Martin Vajsar
Sheriff

Joined: Aug 22, 2010
Posts: 3610
    
  60

I find this feature very useful. Apart from adding to the array, you can easily reorder the elements without having to tidy it up when the last element suddenly stops being last (if you have every element on its own line).

The same is allowed for enums, eg.I generate some Java enums from a database using a script, and not having to bother about the last constant having a semicolon instead of comma is great. Unfortunately, I learned about this feature after I've tailored the scripts to use semicolon instead of comma after the last value....
Leon Omk
Ranch Hand

Joined: Aug 17, 2010
Posts: 75

Thanks guys. Very helpful!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
Obviously whoever wrote that part of the first Java™ compiler thought it was a good idea. You can see from this little bit of C coding that the additional comma was permitted long before Java™ was developed.
Leon Omk
Ranch Hand

Joined: Aug 17, 2010
Posts: 75

Thanks, Campbell. Glad to know Java has this classical part!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why Extra Comma is allowed when constructing an array?