Why can array constants only be used in initializers? [duplicate]

It’s not allowed because the JLS says so. The syntax is only permitted in declarations and in array creation expressions.

The latter provide an alternative way of achieving the same result:

int[] a;
a = new int[]{1, 2, 3, 4};

As to the actual underlying reason for requiring the new T[], my guess is as follows. Consider the following array initializer:

{1, 2, 3, 4}

It can be used to initialize arrays of different types:

new int[]{1, 2, 3, 4};
new float[]{1, 2, 3, 4};
new double[]{1, 2, 3, 4};

If the new T[] bit wasn’t required, I suspect that the bare {1, 2, 3, 4} could cause difficulties during semantic analysis. Here, I am thinking about cases like:

void f(float[] x) { ... }
void f(double[] x) { ... }
void g() {
  f({1, 2, 3, 4});
}

If this syntax were allowed, the language spec would have to deal with the complexity of choosing which function to call.

In a similar vein, it’s not clear what should be the type of {null}. It can be Object[], Integer[], Serializable[] and so on.

And finally, the empty array {} would be the trickiest of all. Here, we can’t even tell if it’s an array of objects or an array of scalars.

Instead of dealing with all these complexities, it seems that the language designers chose to avoid them by requiring the new T[] syntax.

Leave a Comment