Anonymous code blocks in Java

java

Solution

They restrict variable scope.

public void foo()
{
    {
        int i = 10;
    }
    System.out.println(i); // Won't compile.
}

In practice, though, if you find yourself using such a code block that's probably a sign that you want to refactor that block out to a method.

Problem

Are there any practical uses of anonymous code blocks in Java? ``` public static void main(String[] args) { // in { // out } } ``` Please note that this is not about named blocks, i.e. ``` name: { if ( /* something */ ) break name; } ``` .

Original source

Related problems