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?
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_ :.
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 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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With