-2

I know about static initialization blocks and double brace initialization. But what about extra braces in a method.
The compiler does not throw any exception for the following code:

public static void main (String [] args) {
String hello = "Hello";
    {
        System.out.print(hello);
        {{{{{
            System.out.println(" world!");
        }}}}}
    }
}

So why does this work? Shouldn't it throw java.lang.Error?

John
  • 467
  • 1
  • 6
  • 23
  • Q: *"So why does this work?"* - 'Cos it is legal ... though ugly ... Java. Q: *"Shouldn't it throw java.lang.Error?"* No. 1) it is legal Java. 2) Compilation errors don't throw exceptions. (Duh!) – Stephen C Nov 04 '16 at 08:14

2 Answers2

4

Braces defines variable scope in Java, so this is valid, even though you are basically defining multiple equivalent scope.

David Wong
  • 748
  • 3
  • 6
  • "[...] you are basically defining multiple equivalent scope" - This is not correct. The scopes are not identical (but useless, since they do not define any variables). Notice, however, that in Java you cannot overwrite an already existing variable in an inner scope. In C/C++ this would be possible. – Turing85 Nov 04 '16 at 07:34
  • 1
    I meant equivalent in the functional sense, i.e. the scope contains the same set of variables. Hope that's clear now. – David Wong Nov 04 '16 at 15:47
2

The only purpose of the extra braces is to provide scope-limit. The List copy will only exist within those braces, and will have no scope outside of them.

If this is generated code, I assume the code-generator does this so it can insert some code (such as this) without having to worry about how many times it has inserted a List copy and without having to worry about possibly renaming the variables if this snippet is inserted into the same method more than once.

Sometimes you see a construct like that in the code of people who like to fold sections of their code and have editors that will fold braces automatically. They use it to fold up their code in logical sections that don't fall into a function, class, loop, etc. that would usually be folded up.

Liam Larsen
  • 150
  • 2
  • 12