• Post Reply Bookmark Topic Watch Topic
  • New Topic

Extra comma in two dimentional array declareation  RSS feed

 
Chadd Franck
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is in the Sun Certified Java Programmer study guide page 277;

The code works fine but there is an extra comma



but if you notice when int [][] a is created, there is a comma after the 2 in a[0][1]. The program will run with it there or not. Can anyone explain why a , with no following argument is allowed here?

Thanks.
 
Brian Lang
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the Java Language Specification section 10.6 Array initializers:

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


And BTW, that code will technically not compile. The main method's opening brace is a closing brace.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is possible in any Java array, not just an array of arrays. For example, these are completely equivalent:

and

The final comma is simply ignored either way.

Why is this allowed? First, probably because it was legal in C. Much of Java syntax came from C simply because C was popular, and there was no compelling reason to change this. Why was it allowed there? Probably because it can make things a tiny bit easier for programmers at times. For example, some people use a style like this (going back to Java):

If they decide to add an element to the end of this list, they must also remember to add a comma after "baz". However if they add an element in the middle of the list, the comma is already there (but they need a new comma after the new element. It's easy to make mistakes if you're changing things quickly. Consequently, some people prefer to just always put a comma after each array element, even the last. It's just one less detail to worry about. Consistency makes things simpler.
[ December 19, 2008: Message edited by: Mike Simmons ]
 
Brian Lang
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good post, Mike, thanks for that. Makes alot of sense. I don't know how many times I've been in that situation (not in Java, necessarily) and had to track down the extra comma dangling there taunting me.
 
Chadd Franck
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great, I guess I was wondering if there was some hidden aspect to this thing, but there was not, just the obvious staring me in the face.. Thanks for the answer

Brian and Mike... have a good'un
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!