OK, this is one of those things that most people who are just interested in getting their
SCJP should just ignore. The exam is not going to
test you on this bit of esoterica. Really. You can drive yourself crazy worrying about these sort of minutae - don't. Most programmers will never need to know this - the compiler just tells them their code is invalid, and they fix it.
Note that there's really no valid reason to ever try to write a local variable declaration as the only thing inside a loop, because there's no chance that the local variable will ever be used for anything. Anyone who does this is probably just confused about what they're doing.
Java is set up to catch
some of the stupid mistakes we might make while coding, if it's something that is obviously useless like this. Of course there are plenty of other mistakes you can make which the compiler won't catch, so don't count on the compiler too much - but certain classes of errors
are caught by th compiler, and this is one of them. If you get an error message in this case, it doesn't really matter why the compiler is complaining, so much as what was the coder trying to do? If you see this error, you look at the source code:
and ask yourself, what possible use is there to having that statement? None. Nada. No one could ever use val; it's useless. So get rid of it. That's all we really need to know as programmers.
But, for those who are nonetheless wondering how this is addressed by the JLS:
Maybe its a bug? I didn't see anything in the JLS saying its illegal It's not a bug; this is illegal according to the JLS. Though like many things in the JLS, this is far from obvious.
In this case we have to track the grammar productions found throughout the JSL. The grammar for a do statement is defined in
JLS 14.12:
So, what's allowable as a
Statement? That's defined in [url=]JSL 14.5[/url]:
Now I'm not going to follow each of these options separately, but the thing is,
none of the options above can lead to a
LocalVariableDeclarationStatement unless it's nested in a
Block. That path is found by following
Statement to
StatementWithoutTrailingSubstatement to
Block, which is defined in
JLS 14.2:
A
LocalVariableDeclarationStatement can be part of a
BlockStatement, which can be part of
BlockStatements - but to make that part of a
Block, you need the braces.
The short version of this is, despite the name, a
LocalVariableDeclarationStatement is not a
Statement. But a {
LocalVariableDeclarationStatement } is. So you can't have
but you can have
[ December 14, 2003: Message edited by: Jim Yingst ]