0

I just noticed recently, while coding, that surrounding code with braces without any condition (or anything else) lets the code running correctly. For example, the following snippet:

public static void main(String[] args) {
{
    System.out.println("Hello world !");
    {
        System.out.println("Hello subworld !");
        {
            System.out.println("Hello sub-subworld !");
        }
    }
}
}

Gives the following output:

Hello world !
Hello subworld !
Hello sub-subworld !

I would like to know: are there any consequences, deeper into execution, of this kind of practice ? And, is it used in any case and proven to be useful ?

Xan
  • 74,770
  • 16
  • 179
  • 206
Yassine Badache
  • 1,810
  • 1
  • 19
  • 38
  • 4
    Whenever I use it, it is to keep variables in a tighter scope: variables declared inside the block are only in scope inside that block. It can make logical blocks of the method easier to pick out too; but if you need to do that, the method is probably too big, and needs to be split up. – Andy Turner Jul 07 '16 at 13:17
  • You can use the braces for better code style or to tight the scope where your variables are avaiable – CloudPotato Jul 07 '16 at 13:18
  • Variables defined inside such a block vanish when leaving the block. This might be useful for copy-paste-repeating definitions with the same name, or making a variable eligible for garbage collection. – Thorbjørn Ravn Andersen Jul 07 '16 at 13:18
  • Thank you for your answers, I did not know such thing as "anonymous block" in Java, and it sounds pretty useful to tighten up the code. – Yassine Badache Jul 07 '16 at 13:25
  • 1
    @YassineBadache they're not called "anonymous blocks", they are simply ["blocks"](https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-Block). Not knowing about them doesn't mean the question isn't a duplicate, though. – Andy Turner Jul 07 '16 at 13:33
  • It doesn't matter if you knew the nomenclature used by the other question, the only thing that matters is: does the other question contains at least one answer, which answers your question as well. So it is a duplicate. – Tom Jul 07 '16 at 13:33
  • 1
    Ok I didn't understood it that way. Sorry, you're right. – Yassine Badache Jul 07 '16 at 14:01

0 Answers0