Java: Allowed statements after labels

Moritz :

I'm playing around with Java Syntax, so this is question arises purely from curiosity. This piece of code:

http://www.google.com
Object val = 5 <- 4;

does not compile, because a label (http) "must be followed by a statement". The following two variants do compile:

http://www.google.com
{ Object val = 5 <- 4; }

and

Object val;
http://www.google.com
val = 5 <- 4;

In both cases, I switched from a declaration to an expression. This makes me wonder what exactly is a "statement" in Java, but the doc states:

In addition to expression statements, there are two other kinds of statements: declaration statements and control flow statements. A declaration statement declares a variable.

The JLS just says (on labels) that

The Identifier is declared to be the label of the immediately contained Statement.

It does not say anything about "expression statements".

Did I miss something, or is this just an unclear/incorrect specification?

yshavit :

If you read chapter 14 of the JLS a bit more carefully, you'll find that a LocalVariableDeclarationStatement is not a Statement. Not very intuitive of them, is it?

Specifically, in JLS 14.2, we see that:

  • a Block essentially consists of zero or more BlockStatements
  • a BlockStatement is one of:
    • LocalVariableDeclarationStatement
    • ClassDeclaration
    • Statement

So a LocalVariableDeclarationStatement is not a descendant of Statement in the hierarchy, but rather a sibling. They are both types of BlockStatements.

A label must be followed by a true Statement — that is, the specific subtype of BlockStatement that is neither a LocalVariableDeclarationStatement nor a ClassDeclaration. The various subtypes of Statement are listed in 14.5. You will not find LocalVariableDeclarationStatement among them, though you will find ExpressionStatement as a subtype of StatementWithoutTrailingSubstatement.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=448287&siteId=1