Marvin Meller Marvin Meller - 3 months ago 9
Java Question

Is it possible to use braces {} just to subdivide Java code?

I'm quite inexperienced in making GUI's with Swing and now I'm wondering if its possible to use "{" and "}" just to subdivide my code a little bit e.g.

[...]
JFrame f = new JFrame();
JPanel p = new JPanel();
{
JLabel a = new JLabel("Hello");
p.add(a);

JLabel b = new JLabel("World!");
p.add(b);
}
f.add(p);
[...]


I tested it and I don't think it made any difference... Am I wrong?

Thanks in advance

Answer

Yes, it's possible, you can use a block anywhere you can use an individual statement. Variables declared within that block will only be valid within the block. E.g.:

void method() {
    String allThisCodeCanSeeMe;

    // ...

    {
        String onlyThisBlockCanSeeMe;
        // ...
    }

    {
        String onlyThisSecondBlockCanSeeMe;
        // ...
    }

    // ....
}

But: Usually, if you find yourself wanting to do something like this, it suggests that you need to break the code into smaller functions/methods, and have what's currently your one method call those smaller parts:

void method() {
    String thisMethodCanSeeMe;

    // ...

    this.aSmallerMethod();        // <== Can pass in `thisMethodCanSeeMe`
    this.anotherSmallerMethod();  // <== if needed

    // ...
}

private void aSmallerMethod() {
    String onlyThisMethodCanSeeMe;
    // ...
}

private void anotherSmallerMethod() {
    String onlyThisSecondSmallerMethodCanSeeMe;
    // ...
}
Comments