Search code examples
javablock

Is there a practical use for an unspecified block in Java?


Possible Duplicate:
Anonymous code blocks in Java

I learned the other day (on SO) that

public method() {
    someCode()
    {
        Object value = localCode();
        doSomethingWith(value);
    }
    moreCode();
}

Is valid Java and it makes the block containing value local to that region, so value only exists in that block.

Is there any practical use for this? If not, why doesn't Java give a warning for this (silly) use of {}?


Solution

  • I use this in tests where I want to repeat different scenarios.

    {
        long start = System.nanoTime();
        // do something
        long time = System.nanoTime() - start;
        // print result.
    }
    {
        long start = System.nanoTime();
        // do something else
        long time = System.nanoTime() - start;
        // print result.
    }
    {
        long start = System.nanoTime();
        // do something else again.
        long time = System.nanoTime() - start;
        // print result.
    }
    

    This allows be to copy the code without having to change the names, or risk re-using variables.