Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Allowed statements after labels

Tags:

java

syntax

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?

like image 426
Moritz Avatar asked Mar 28 '17 06:03

Moritz


People also ask

What are Labelled statements in Java?

Java labeled blocks are logically similar to goto statements in C/C++. A label is any valid Java identifier followed by a colon. For example, outer: , inner: , customLabel: , label_ :.

How do you break a label in Java?

The break Statement This is the output of the program. The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.

What are statements in Java?

What is statement in Java? In Java, a statement is an executable instruction that tells the compiler what to perform. It forms a complete command to be executed and can include one or more expressions. A sentence forms a complete idea that can include one or more clauses.


1 Answers

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.

like image 108
yshavit Avatar answered Sep 28 '22 11:09

yshavit