Forum Stats

  • 3,837,185 Users
  • 2,262,234 Discussions
  • 7,900,218 Comments

Discussions

last comma in array

843853
843853 Member Posts: 3,739
edited May 18, 2005 3:41AM in Java Programming
I think that it wasn't possible in the previous versions of java. The next code compiles fine with jdk1.5.0:
public class Test {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3,};  // <- last comma
        
        String[] arr2;
        arr2 = new String[]{"a", "b", "c",};  // <- last comma
        
        float[] arr3 = {,};  // <- last comma

    }
}
Is it a bug or a feature?

Comments

  • 843853
    843853 Member Posts: 3,739
    It'a feature. And it worked (or should have) in previous versions. I think it is a way to ease the work for automated code generation.
    Check out the Java Language Specification:

    --

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

    The length of the constructed array will equal the number of expressions.

    The expressions in an array initializer are executed from left to right in the textual order they occur in the source code. The nth variable initializer specifies the value of the n-1st array component. Each expression must be assignment-compatible (�5.2) with the array's component type, or a compile-time error results.

    If the component type is itself an array type, then the expression specifying a component may itself be an array initializer; that is, array initializers may be nested.

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

    --

    http://java.sun.com/docs/books/jls/
This discussion has been closed.