Search code examples
javasyntaxscopebraces

Java block without an associated keyword


Out of curiosity I tried this out to see if it was valid code inside a method:

{
    // code
}

And it is! All it does is limit the scope:

{
    int i = 1;
}

i = 2; // error

This is nice for e.g. when I've needed to do something that looks structurally like this:

int i = 0;
for (; i < number; i++) {...}

doSomethingWithTheCount(i);

But I'd like to limit the scope of i:

{
    int i = 0;
    for (; i < number; i++) {...}

    doSomethingWithTheCount(i);
}

And indeed I can. Is this useful for anything else or just obscure?

Additionally, I've read that limiting the scope of an object is a good way to ensure it is garbage collected sooner so potentially doing this is beneficial in that regard. Is that correct?


Solution

  • There is nothing inherently wrong in declaring anonymous blocks, so you don't have to worry about it as such. Some people may have opinions about it following Java coding conventions or other ideas of a more or less aesthetic nature, but that's subjective and up to you to decide the validity of. I, on my hand, would have no such issues with it.

    However, it is not correct that it helps garbage collection. In the compiled bytecode, the local variables persist beyond the end of the block's scope and will retain their values unless you explicitly clear them to null; the block only affects symbol allocation in the Java source, and does not translate to anything that the JVM sees.

    Additionally, it may be worth noting that you can also use these kinds of blocks for control-flow purposes, like this:

    foo: {
        /* ... */
        if(bar)
            break foo;
        /* ... */
    }
    

    Unfortunately, Java does not support continue foo for custom looping logic. :(