Home  >  Article  >  Java  >  The legal use of JAVA statement tags, and what is the use of {} statement blocks?

The legal use of JAVA statement tags, and what is the use of {} statement blocks?

高洛峰
高洛峰Original
2017-01-22 16:42:241512browse

For example, write a piece of code like this:

int i; 
{ 
int j=1; 
i=j; 
}

If this code exists in the class definition area, then we know that it is an ordinary statement block used to initialize the content of the class attribute. It will be in the class It is called when instantiated, and some methods can be executed in it.
In many instances, it will be used in singleton and other modes. Add a static before it to initialize content for complex classes, which can avoid some runtime exceptions caused by the loading sequence.
But what if this code appears in a method?
It basically makes no sense at all. In my previous thoughts, it was just a format for enclosing code, nothing else.
Today I wrote some code related to "statement label":

label17: int i; 
int j; 
ThreadGroup[] arrayOfThreadGroup; 
if (flag) 
break label17; 
return 0;

The exception "Syntax error on token ":", { expected after this token" occurred at the ":" position.
That is to say, when the code cannot exist in a single line (int i must have a clear instantiation\assignment position inside the method body), label17 needs to be marked with a statement block.
The correct format is:

label17: { 
int i; 
int j; 
ThreadGroup[] arrayOfThreadGroup; 
if (flag) 
break label17; 
return 0; 
} 
或者: 
   label17: 
int i; 
int j; 
ThreadGroup[] arrayOfThreadGroup; 
if (flag){ 
break label17; 
return 0;}

Let’s look at the wrong usage:

label13: int x = 0;

Obviously, there is a default single-line statement block after the label, and this x can be anywhere in the future None can be used, error. The prompt is as follows:
Multiple markers at this line
- x cannot be resolved to a variable
- Syntax error on token "int", delete this token
There are two correct formats:

int x = 0; 
label13: x = 0; 
或者 
label13:{ int x = 0;}

So I speculated that a previous misunderstanding was that in usages such as for(){} and if(){}, logical if() and statement block {} should be two independent syntaxes.

For more legal uses of JAVA statement tags and what is the use of {} statement blocks, please pay attention to the PHP Chinese website for related articles!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn