开发者

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 w开发者_开发百科ithin the {} will be released right after execution exits {}, right, because I can't access these outside the {} anymore?


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.


This gives him a nested scope to declare "more local" variables.

I guess that the variables declared within the {} will be released right after exit {}, right, because I can't access these outside the {} anymore?

Depends on your definition of "release" (they will most likely not be garbage collected until the method ends, so if this is important, you might want to null them out), but yes.

Other rarely seen uses of curly brackets include class and instance initializers:

class A {
   static {
      // some class initialization code
   }

   {
      // some instance initialization code
   }

 }


The fact that the author put those variables in {} indicates the scope of those variables will only be that of the method defined by the {}; in turn, those variables will be up for garbage collection once method finishes execution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜