3

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.