Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does two consecutive blocks of code {}{} do? [duplicate]

Tags:

java

Possible Duplicate:
Anonymous code blocks in Java

I just came across the following.

if ( test ) {
    {
        // statements 1
    }
    {
        // statements 2
    }
}

It is the first time I've seen this. How does it work?

like image 381
Ricardo Sanchez Avatar asked Feb 17 '12 14:02

Ricardo Sanchez


3 Answers

It's is just writing two different blocks of code in order to hide local variables.

From the answer to the question "Anonymous code blocks in Java":

Blocks restrict variable scope.

public void foo()
{
    {
        int i = 10;
    }
    System.out.println(i); // Won't compile.
}

In practice, though, if you find yourself using such a code block then it's probably a sign that you want to refactor that block out to a method.

like image 137
4 revs, 3 users 59% Avatar answered Sep 20 '22 21:09

4 revs, 3 users 59%


Two examples of where this can be (slightly) useful - in unit tests, and in GUIs, both of which often involve repetitive code:

It's useful in GUI building, where it is incredibly easy to cut-and-paste lines relating to one component and forget to update them for the new component, leading to hard-to-find bugs, e.g.:

    JButton button1 = new JButton("OK");
    button1.setEnabled(false);
    button1.setAlignmentX(-1);

    JButton button2 = new JButton("Apply");
    button1.setEnabled(false);
    button1.setAlignmentX(-1);

Oops, I just configured button1 twice. If you put each button in its own block, then this mistake is picked up by the compiler. Again, you could create each button in a separate method, but that may make it hard to see what is going on (especially given the lack of keywords parameters in Java):

JButton button_ok = makeButton("OK", false, -1);
JButton button_apply = makeButton("Apply", true, 1);
// what exactly is being set here?

...

// much later:
private static JButton makeButton(String name, boolean enabled,
        int alignment)
{
    JButton button = new JButton(name);
    button.setEnabled(enabled);
    button.setAlignmentX(alignment);
    return button;
}

...and you may end up with numerous methods, each handling different variations of parameters, and each only being used maybe twice.

like image 21
DNA Avatar answered Sep 21 '22 21:09

DNA


The two blocks are independent. So, whatever variables you may have in the first block won't be accessible in the second block - or anywhere outside the first block. It's called code isolation or scoping.

like image 10
Kimi Avatar answered Sep 19 '22 21:09

Kimi