Java – use {} after semicolon

See English answers > anonymous code blocks in java7

MenuItem menu1 = menu.add(0,"Item 1");
{
  menu1.setIcon(R.drawable.ic_launcher);
  menu1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}

How do I use curly braces after semicolons? Here are some concepts I don't understand

Solution

In this case, they are completely optional and have no side effects at all In your example, the only purpose is to make the code easier to read by assigning properties intended to belong to the control You can also do it without braces However, if you reformat the code with a tool, the indentation may have passed

However, if you have a method and you put {} there, you can create a new variable range:

void someMethod() {
    {
         int x = 1;
    }
    // no x defined here
    {
         // no x here,so we may define a new one
         string x = "Hello";
    }
}

You can start a new scope anywhere in the method, where you can start statements (variable declarations, method calls, loops, etc.)

Note: when you have an IF statement, you also use this brace to create a new variable range

void someMethod() {
    if (someThing) {
         int x = 1;
    }
    // no x defined here
    if (somethingElse) {
         // no x here,so we may define a new one
         string x = "Hello";
    }
}

The same is true for, trying, grasping, etc If you think of it, even the method body braces work this way: they create a new scope, which is a "layer" above the class scope

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>