Search code examples
javaarrayssyntaxinline

What type of syntax is the Java "new Type[]{...}" array literal initialization?


What grabbed my attention, which I cannot explain to myself, is a thought about this well known code:

String[] str = new String[]{"a","b","c"};

Is new String[] a cast? If it is, why do we use new and no brackets? We would cast as in:

float i = (float) 3;

It also seem not to be a constructor, because then we would use it like a function call (e.g new String[](...)).

So what kind of syntax is it, and do we have more of that kind in Java?


Solution

  • This syntax is an example of an 10.6. Array Initializer as part of an 15.10.1. Array Creation Expression.

    An array initializer may be specified in a field declaration (§8.3, §9.3) or local variable declaration (§14.4), or as part of an array creation expression (§15.10.1), to create an array and provide some initial values.

    new String[]
    

    is an array creation expression and

    {"a","b","c"}
    

    is an array initializer.

    Since there are no dimension expression in your array creation expression (i.e. nothing inside the square brackets), there must be an array initializer:

    If there are no dimension expressions, then there must be an array initializer. A newly allocated array will be initialized with the values provided by the array initializer as described in §10.6.