LearningMath
LearningMath

Reputation: 861

Array creation syntax in Java

Here is the grammar for array creation in Java:

ArrayCreationExpression:
new PrimitiveType DimExprs [Dims]
new ClassOrInterfaceType DimExprs [Dims]
new PrimitiveType Dims ArrayInitializer
new ClassOrInterfaceType Dims ArrayInitializer

DimExprs:
DimExpr {DimExpr}

DimExpr:
{Annotation} [ Expression ]

Dims:
{Annotation} [ ] {{Annotation} [ ]}

Why here: new PrimitiveType DimExprs [Dims] Dims is in brackets? If it is in brackets then I can write this: new int [2][2] [[] []] where [2][2] is the DimExprs part and [] [] is the Dims part. What am I doing wrong here?

Upvotes: 3

Views: 91

Answers (1)

LearningMath
LearningMath

Reputation: 861

It seems that the answer was in front of my eyes but somehow i missed it. Here is the reason from the Java Specification:

The syntax [x] on the right-hand side of a production denotes zero or one occurrences of x. That is, x is an optional symbol. The alternative which contains the optional symbol actually defines two alternatives: one that omits the optional symbol and one that includes it.

This means you can write String[][][] s = new String[2][][];

Link: https://docs.oracle.com/javase/specs/jls/se8/html/jls-2.html#jls-2.4

Upvotes: 1

Related Questions