Details and examples of java statement blocks

  • 2020-05-27 05:44:27
  • OfStack

java block

I remember when I first read the programming books of C, C++ and Java, they introduced statement blocks, but I didn't understand what statement blocks were at that time. There is also talk in daqo about organizing statements with similar functions into 1 statement block, and then separating them from other statement blocks with blank lines. But this is only in the human understanding of the statement block, not the real programming language meaning of the statement block.

The programmatic definition, as I understand it, should be a collection of related 1 statements with the same variable scope, which seems to be enclosed by {}, such as logic in a control structure. I think the most important point is the variable scope, that is, if you can use the same local variable, then the statement block in the program sense. Here's 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, you can still use the variables defined earlier by case, so the entire switch() {} is one statement block.

But if you add a block flag to each case statement, it's not the same:


@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; 
} 

The addition of {} separates the two case statements to form two statement blocks, each with its own variable scope, which does not matter to each other, even if the name is the same or it is defined again.

The purpose of this explanation is to use {} as often as possible to form a real block of statements. The greatest benefit is that it can be used to form a variable scope to avoid the scope of variables being too large, which improves readability and reduces the possibility of errors.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: