Can braces {} be used to separate Java code?

I'm pretty inexperienced in creating a GUI with Swing, and now I'm wondering if it is possible to use "{" and "}" to separate my code a bit, for example.

[...] 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 mattered ... Am I mistaken?

Thanks in advance

+7
java swing
source share
3 answers

Yes, perhaps you can use the block anywhere you can use a separate statement. Variables declared in this block will be valid only within the block. For example:.

 void method() { String allThisCodeCanSeeMe; // ... { String onlyThisBlockCanSeeMe; // ... } { String onlyThisSecondBlockCanSeeMe; // ... } // .... } 

But . Usually, if you want to do something like this, this assumes that you need to break the code into smaller functions / methods and have what your method is currently being called the less part:

 void method() { String thisMethodCanSeeMe; // ... this.aSmallerMethod(); // <== Can pass in `thisMethodCanSeeMe` this.anotherSmallerMethod(); // <== if needed // ... } private void aSmallerMethod() { String onlyThisMethodCanSeeMe; // ... } private void anotherSmallerMethod() { String onlyThisSecondSmallerMethodCanSeeMe; // ... } 
+18
source share

The only difference braces make is that any variables declared in these braces are invisible outside of them.

In the example:

 JPanel p = new JPanel(); { JLabel a = new JLabel("Hello"); p.add(a); int b = 5; } b = 10; // Compiler error 
+4
source share

{} are a "block" of code, and adding will no longer have any effect. Indentation is an accepted way to make material more readable. You can add more braces, but you don't agree with the way most of us write Java.

+2
source share

All Articles