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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With