Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top