You can't declare a variable there (the current error, from Java 8, is error: variable declaration not allowed here
). If you think about it, it makes sense: You haven't created a new scope (but using a block), but you're creating a situation where sometimes in the current scope, there will be a statement
variable, and other times there won't. E.g.:
if (condition)
Statement statement = con.createStatement();
// Does `statement` exist here? What would Schrodinger say?
If you use a block, it clarifies the matter: The variable exists, but only within the block.
if (condition) {
Statement statement = con.createStatement();
// `statement` exists here
}
// `statement` does not exist here
If you want statement
to exist in the current scope, you have to separate your declaration from your initialization:
Statement statement;
if (condition)
statement = con.createStatement();
But then you run into the issue that statement
may not have been initialized. To avoid that, you have a couple of options:
Statement statement;
if (condition)
statement = con.createStatement();
else
statement = null;
or
Statement statement = condition ? con.createStatement() : null;
Or of course, just use the block and only use statement
within it. FWIW — and this is totally up to you — I (and many style guides) recommend always using blocks, because not doing so can introduce maintenance issues when you need (inevitably!) to add a second statement to the body of the if
...