Anonymous code blocks in Java

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.

Leave a Comment