Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!