java statement block
I still remember that when I first read C, C++ and Java programming books, there were introduction statement blocks on it, but I didn’t understand what a statement block was. The "Code Collection" also says that statements with similar functions should be organized together to form statement blocks, and then separated from other statement blocks by blank lines. But this is just a statement block in human understanding, not a statement block in the true sense of programming language.
In my understanding, the program definition should be a collection of related sets of statements with the same variable scope. It seems that it should be enclosed with {}, such as the logic in the control structure. I think the most critical point is the scope of the variable, that is, if the same local variable can be used, it is a statement block in the program sense. Let’s take a look at an example:
@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 variable defined in the previous case can still be used, so the entire switch() {} is a statement block.
But if you add a statement block flag to each case statement, it will be different:
@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; } Adding {} separates the two case statements and forms two statement blocks. They have their own variable scopes and do not affect each other. Even if they use the same name, it doesn't matter if they define it again.
The purpose of explaining these is to use as many {} as possible to form a real statement block. The biggest advantage is that it can form a variable scope and avoid the scope of the variable being too large, which improves readability and reduces the possibility of errors.
Thank you for reading, I hope it can help you. Thank you for your support for this site!