Multiple open and close curly brackets inside method. - Java

前端 未结 2 1606
抹茶落季
抹茶落季 2020-12-05 14:22
 public class MyTestClass {

    public static void main(String[] args) {
        new MyTestClass().myMethod();
    }

    public void myMethod(){
        {
                 


        
相关标签:
2条回答
  • 2020-12-05 14:45

    It is not common practice to do this kind of thing, and I wouldn't do it normally.

    Those inner blocks ( i.e. { ... } ) can serve a couple of purposes:

    • Blocks limit the scope of any variables declared within them; e.g.

      public void foo() {
          int i = 1;
          { 
              int j = 2;
          }
          // Can't refer to the "j" declared here.  But can declare a new one.
          int j = 3;
      }
      

      However, I wouldn't recommend doing this. IMO, it's better to use different variable names OR refactor the code into smaller methods. Either way, most Java programmers would regard the { and } as annoying visual clutter.

    • Blocks can be used to attach labels.

      HERE : {
          ...
          break HERE;  // breaks to the statement following the block
          ...
      }
      

      However, in practice you hardly ever see labelled break statements. And because they are so unusual, they tend to render the code less readable.

    0 讨论(0)
  • 2020-12-05 14:45
    public void stuff() {
      int i = 48;
    
      { 
        int i = 21;
        System.out.println(i); // prints 21
      }
      System.out.println(i); // prints 48
    }
    

    Basically, it's a way to create scopes smaller than entire function... Benefit?.. have the people stare at your code longer before they understand it... IMO it's bad style and should be avoided

    0 讨论(0)
提交回复
热议问题