John John - 1 year ago 92
Java Question

Does extra braces inside a method have any usage?

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.println(" world!");

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download