Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

non-braces if block variable definition gives an error

Tags:

java

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.

like image 334
rdonuk Avatar asked Aug 23 '14 19:08

rdonuk


1 Answers

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.

like image 65
Sergey Kalinichenko Avatar answered Oct 16 '22 17:10

Sergey Kalinichenko