9

In an example of android code given in a book regarding action bar, the sample given is as the following:

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

How is using curly braces after a semi-colon possible? There is clearly some concept that I do not understand right here.

Arif Samin
  • 257
  • 1
  • 9
  • 3
    as far as I know this is the same as if you'd leave the { }. menu.add is one command, menu.setIcon is the next, menu.setShowAsAction the next. Braces can be used to declare code blocks. – damian Jun 13 '13 at 10:27
  • Only a duplicate of that *if you know* it is an anonymous code block. – Raedwald Jun 13 '13 at 12:36

3 Answers3

17

They are completely optional in this case and have no side-effect at all. In your example it sole serves to purpose of making the code more readable by intending the property assignment which belong to the control. You could as well do it without the braces. But if you'd use a tool to reformat your code, the indentation is likely gone.

However, if you have a Method and you put {} in there, you can create a new variable scope:

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 a Method where you can start a statement (a variable declaration, a method call, a loop etc.)

Note: When you have for example an if-statement you also create a new variable scope with that braces.

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 while, for, try, catch and so on. If you think about it even the braces of a method body work in that way: they create a new scope, which is a "layer" on top of the class-scope.

Mene
  • 3,739
  • 21
  • 40
15

It's called anonymous code blocks, they are supposed to restrict the variable scope.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
DevZer0
  • 13,433
  • 7
  • 27
  • 51
0

Those are Initialization Blocks.

I don't think this is the correct usage of initialization block. Apart from the example you have produced, these blocks are just used for initialization purpose. Click Here for detailed view.

R9J
  • 6,605
  • 4
  • 19
  • 25
  • 1
    They *could* be an initializer, but they could also be a simple block statement within a method. We can't tell without seeing the context. – Stephen C Jun 13 '13 at 10:45
  • sure, the usage is completely depends upon the developer – R9J Jun 13 '13 at 10:46