When trying to compile the following
public class Test {
public void method(String foo) {
// This compiles if the curly braces are uncommented
if(foo instanceof Object) // {
Object bar = (Object) foo;
// }
}
}
I get the following errors
javac -Xlint:all Test.java
Test.java:5: error: not a statement
Object bar = foo;
^
Test.java:5: error: ';' expected
Object bar = foo;
^
2 errors
Why does Object bar = (Object) foo; need to be in a block for the code to compile?
Because it’s pointless to declare a variable when that’s the only statement in the block. The declaration is meaningless, as you won’t be able to refer to the variable in any subsequent code. (The scope of the variable would be just the declaration.)
Basically, the compiler is stopping you from doing something pointless.
In terms of the specification, this is the production you’re trying to use (section 14.9 of the JLS):
Now the Statement production is defined by section 14.5.
Note there’s no LocalVariableDeclarationStatement there. That only occurs in the BlockStatement production, defined in section 14.4 of the JLS.