braces if block variable definition gives an error

if(true)
     String str;

Hi, the code above gives an error like that:

Multiple markers at this line
- str cannot be resolved to a variable
- Syntax error on token "String", AssignmentOperator expected after this token

Why there is an error like this? Of course I know str will be unreachable after defined. But java doesn't gives an explanation like that. Just seemed odd to me.


This is because you put a declaration in a protected block of the conditional. However, Java declarations are not considered statements according to Java syntax.

Declarations are allowed to be mixed with statements as part of blocks enclosed in curly braces, but a single declaration is not considered a statement. This makes perfect sense, because the variable that you declare is not usable: if you wanted a declaration-initialization for its side effect, such as

if (true)
    String str = someFunction();

you could use an expression statement without declaring a variable that you wouldn't be able to use anyway:

if (true)
    someFunction();

Therefore, if you put a declaration by itself in a conditional or a loop, the compiler is certain that you made a mistake, and produces an error message to alert you to the problem.

链接地址: http://www.djcxy.com/p/59502.html

上一篇: 通用返回类型上限

下一篇: 如果块变量定义给出错误,则使用大括号