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.
Place one space after a comma, a semicolon, and other forms of punctuation falling within a sentence.
When a transitional expression appears between independent clauses, the transition is preceded by a semicolon and usually followed by a comma.
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.
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.
It's called anonymous code blocks, they are supposed to restrict the variable scope
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With