Java. It is not possible to create objects in a short line if

Recently, I started programming in Java again after a short break, and while doing a project for a friend, I noticed something strange: you can't seem to create objects in shorthand ifs, e.g .:

if( condition )
     Statement statement = con.createStatement();

      

(I'm just shortening the code for simplicity).

I am getting the error that Statement

(class from package java.sql

) cannot be resolved to variable, however if I were to copy the code using parentheses it would work fine.

I am guessing this is some kind of problem with the compiler turning this into a multi-line statement, but I'm not sure if I would like to know the reason for this behavior, thanks in advance!

+3


source to share


2 answers


You cannot declare a variable here (current error since Java 8 is equal error: variable declaration not allowed here

). If you think about it, it makes sense: you haven't created a new scope (but you are using a block), but you create a situation where sometimes there will be a variable in the current scope statement

and other times it won't. For example:.

if (condition)
    Statement statement = con.createStatement();

// Does `statement` exist here? What would Schrodinger say?

      

If you use a block, it clarifies the question: a variable exists, but only within a block.

if (condition) {
    Statement statement = con.createStatement();
    // `statement` exists here
}
// `statement` does not exist here

      

If you want to statement

exist in the current scope, you need to separate your declaration from your initialization:

Statement statement;

if (condition)
    statement = con.createStatement();

      



But then you ran into the problem that it statement

might not initialize. To avoid this, you have several options:

Statement statement;

if (condition)
    statement = con.createStatement();
else
    statement = null;

      

or

Statement statement = condition ? con.createStatement() : null;

      

Or of course, just use a block and only use statement

within it. FWIW - and it's entirely up to you - I (and many style guides) recommend always using blocks, because not doing so can lead to maintenance issues when you need to (inevitably!) Add a second statement to the body if

...

+7


source


According to the Java specification ,

  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)

      



If you do not complete a statement in curly braces, it immediately goes out of scope.

More details here: fooobar.com/questions/97269 / ...

+2


source







All Articles