For example, write a piece of code like this:
Copy the code code as follows:
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 class attributes. It will be called when the class is 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 a little code related to "statement tags":
Copy the code code as follows:
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:
Copy the code code as follows:
label17: {
int i;
int j;
ThreadGroup[] arrayOfThreadGroup;
if (flag)
break label17;
return 0;
}
or:
label17:
int i;
int j;
ThreadGroup[] arrayOfThreadGroup;
if (flag){
break label17;
return 0;}
Let’s look at an incorrect usage:
Copy the code code as follows:
label13: int x = 0;
Obviously, there is a default single-line statement block after the label. This x cannot be used anywhere in the future, error. The tips are 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:
Copy the code code as follows:
int x = 0;
label13: x = 0;
or
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.