I still remember that when I first read C, C ++, and Java programming books, I introduced the statement block, but I didn't really understand what it was. Code Daquan also says that statements with similar functions should be organized together to form statement blocks, and then separated with other statement blocks by blank lines. However, this is only a statement block in human understanding, not a statement block in the true sense of the program language.
In my understanding, the definition on the program should be a set of related statements with the same variable scope. It seems that it should be included in, for example, the logic in the control structure. In my opinion, the most critical point is the variable scope. That is to say, if the same local variable can be used, it is the statement block in the program sense. Let's look at an example:
Copy codeThe Code is as follows: @ Override
Public boolean onOptionsItemSelected (MenuItem item ){
Switch (item. getItemId ()){
Case MENU_GOTO_FILEANT:
Intent I = new Intent ();
I. setClass (this, FileAntActivity. class );
StartActivity (I );
Break;
Case MENU_TEST_LINEARLAYOUT:
I. setClass (this, LinearLayoutTest. class );
StartActivity (I );
Break;
Default:
Break;
}
Return true;
}
For the second case statement, the variables defined in the previous case can still be used, so the entire switch () {} is a statement block.
However, if you add the statement block flag to each case statement, it will be different:Copy codeThe Code is as follows: @ Override
Public boolean onOptionsItemSelected (MenuItem item ){
Switch (item. getItemId ()){
Case MENU_GOTO_FILEANT :{
Intent I = new Intent ();
I. setClass (this, FileAntActivity. class );
StartActivity (I );
Break;
}
Case MENU_TEST_LINEARLAYOUT :{
Intent I = new Intent ();
I. setClass (this, LinearLayoutTest. class );
StartActivity (I );
Break;
}
Default:
Break;
}
Return true;
}
When {} is added, the two case statements are separated to form two statement blocks. They have their respective variable scopes and do not affect each other. That is, they use the same name, or define it again.
The purpose of this explanation is to use {} as much as possible to form a true statement block. The biggest benefit is that it can form a variable scope to avoid a variable scope being too large, this improves readability and reduces the possibility of errors.