Home > OS >  What is the Java grammar that allows "new int[] {0}[0] = 1;" to compile?
What is the Java grammar that allows "new int[] {0}[0] = 1;" to compile?

Time:10-07

I am using The Java® Language Specification Java SE 8 Edition as a reference.

Example class:

class MyClass {

  void method() {
    new int[] {0}[0] = 1;
  }

}

The code new int[] {0}[0] = 1 should be an Assignment, as index 0 of the created array is being assigned the value 1.

An Assignment is comprised of a LeftHandSide, AssignmentOperator, and an Expression. In this example, the LeftHandSide should be new int[] {0}[0].

A LeftHandSide is either an ExpressionName, FieldAccess, or ArrayAccess. In this example, the LeftHandSide should be an ArrayAccess.

The problem lies with ArrayAccess. ArrayAccess is defined as being either an ExpressionName (not the case for this example) or a PrimaryNoNewArray, and then an Expression between brackets.

The code new int[] {0} is an ArrayCreationExpression. A Primary expression is either an ArrayCreationExpression or a PrimaryNoNewArray. So to me, it seems like the second case for ArrayAccess should be Primary and not PrimaryNoNewArray.

I know the JLS doesn't have explicit grammar for everything, such as parenthesized Expressions or parenthesized LeftHandSides, but this seems to be an error. I checked the most recent spec (Java SE 17) and the grammar for ArrayAccess is unchanged.

CodePudding user response:

It looks like strictly speaking, this doesn't conform with the grammar as specified. But at least, it does make sense for a compiler to allow it: the reason PrimaryNoNewArray is used instead of Primary here is so that an expression like new int[1][0] cannot be ambiguously parsed as either a 2D array or as an array access like (new int[1])[0]. If the array has an initializer like new int[]{0}[0] then the syntax is not ambiguous because this cannot be parsed as creating a 2D array.

That said, since the JLS doesn't specify that it's allowed, it could be treated as either an implementation detail or a bug in the compiler which allows it.

  • Related