A single-line loop with a mandatory pair of braces in Java

When you declare a variable (main in this case):

Main main = new Main();

it doesn’t count as a statement, even if it has side-effects. For it to be a proper statement, you should just do

new Main();

So why is

... {
    Main main = new Main();
}

allowed? { ... } is a block of code, and does count as a statement. In this case the main variable could be used after the declaration, but before the closing brace. Some compilers ignore the fact that it’s indeed not used, other compilers emit warnings regarding this.

Leave a Comment