Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using { } after semicolon [duplicate]

Tags:

java

android

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.

like image 538
Arif Samin Avatar asked Jun 13 '13 10:06

Arif Samin


People also ask

Do you double space after a semicolon?

Place one space after a comma, a semicolon, and other forms of punctuation falling within a sentence.

What to use after semicolons?

When a transitional expression appears between independent clauses, the transition is preceded by a semicolon and usually followed by a comma.

Is it okay to use and after a semicolon?

A semicolon isn't the only thing that can link two independent clauses. Conjunctions (that's your ands, buts, and ors) can do that too. But you shouldn't use a semicolon and a conjunction. That means when you use a semicolon, you use it instead of the ands, buts, and ors; you don't need both.


2 Answers

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.

like image 105
Mene Avatar answered Oct 05 '22 13:10

Mene


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

like image 36
DevZer0 Avatar answered Oct 05 '22 13:10

DevZer0