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. :(