Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is alone { code } in Java for?

I recently read some code that uses a special syntax regarding {}, I've asked a more experienced Java developer, but he also can't answer.

public void doSomething() {
    someWorks();
    {
        someVariables;
        someMoreWorks();
    }
    someEvenWorks();
    {
        ...
    }
}

Why does the code author put these lines inside {}? I guess that the variables declared within the {} will be released right after execution exits {}, right, because I can't access these outside the {} anymore?

like image 724
Luke Vo Avatar asked Sep 07 '11 13:09

Luke Vo


1 Answers

Yes, the only difference is for scoping.

Occasionally this can be useful for throwaway code such as micro-benchmarks where you want to be able to cut and paste a block and make a minor change, then potentially reorder the blocks.

I would rarely (if ever) have something like this in "real" code though.

like image 180
Jon Skeet Avatar answered Nov 13 '22 16:11

Jon Skeet