This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.
What is the Java variable scope in the if statement?
The following code shows a compilation error
if(true)
int a = 10;
else
int b = 20;
Copy the code
No compilation error occurs if you change it to the following code:
if(true) {
int a = 10;
}
else {
int b = 20;
}
Copy the code
Is there any language standard for why the first syntax is wrong?
Answer a
The Java specification specifies the form of if-then-else statements as follows:
IfThenElseStatement:
if ( Expression ) StatementNoShortIf else Statement
Copy the code
Where statements and StatementNoShortIf can be anything, including blocks (code enclosed in braces), assignments (to already-declared variables), other if statements, and so on.
It is worth noting that if you declare a variable (such as int a; Or int a=10;) Missing from the list causes a compilation error.
For the full list, you can read the Java specification here:
- Docs.oracle.com/javase/spec…
Answer two
Let’s examine what your first code example means for language design.
if(condition)
int a = 10;
else
int b = 20;
Copy the code
That means that in our case, we defined either a or B. Since we don’t know which branch is used, we have no way of knowing how to use a or b after the if statement. (Which, if we could, might lead to strange errors).
So as language designers, we decided that A and B would be invisible outside their respective branches to avoid these weird bugs. However, since block-free branches can only have one statement, it makes no sense for us to declare a (or B) immediately inaccessible/unavailable. Therefore, we decided that variable declarations were only allowed with blocks. A block can have multiple statements, so variables declared in that block can be used by other statements.
Java’s designers probably applied similar reasoning, so they decided to allow declarations only in blocks. This is done through the definition of if (JLS 14.9) :
IfThenStatement:
if ( Expression ) Statement
IfThenElseStatement:
if ( Expression ) StatementNoShortIf else Statement
IfThenElseStatementNoShortIf:
if ( Expression ) StatementNoShortIf else StatementNoShortIf
Copy the code
(JLS) 14.5
Statement:
StatementWithoutTrailingSubstatement
...
StatementNoShortIf:
StatementWithoutTrailingSubstatement
...
StatementWithoutTrailingSubstatement:
Block
...
Copy the code
(JLS 14.2):
Block:
{ [BlockStatements] }
BlockStatements:
BlockStatement {BlockStatement}
BlockStatement:
LocalVariableDeclarationStatement
ClassDeclaration
Statement
Copy the code
The article translated from Stack Overflow:stackoverflow.com/questions/2…