Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

swing

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

like image 966
Marvin Avatar asked Dec 05 '15 17:12

Marvin


2 Answers

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;
    // ...
}
like image 154
T.J. Crowder Avatar answered Oct 06 '22 01:10

T.J. Crowder


The only difference the braces make is that any variables declared within those braces are invisible outside of them.

For the example:

JPanel p = new JPanel();
{
   JLabel a = new JLabel("Hello");
   p.add(a);

   int b = 5;
}

b = 10; // Compiler error
like image 20
Mohammed Aouf Zouag Avatar answered Oct 06 '22 00:10

Mohammed Aouf Zouag