Compiler error when declaring a variable inside if condition and no curly braces

Because the language spec says so:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html

A declaration introduces an entity into a program and includes an identifier (§3.8) that can be used in a name to refer to this entity. A declared entity is one of the following:

A local variable, one of the following:
* A local variable declared in a block (§14.4)
* A local variable declared in a for statement (§14.14)

Your first example is declaring i inside a block (denoted by curly braces). Your second isn’t, nor is it a for statement.

Edited to add: Which just makes commons sense. If it were allowed, it would be useless. It would immediately fall out of scope.

Leave a Comment

tech