Compiler error for single line if
Hi all,
I found an interesting quirk, recently. I've condensed the problem into the following simple test class.
publicclass Main{
publicstaticvoid main(String[] args){
finalboolean myBoolean = args.length > 1;
if (myBoolean){
finaldouble result = doIt();
}
}
publicstaticdouble doIt(){
return System.currentTimeMillis();
}
}
Turns out that the variable declaration on line 9 (it doesn't have to be calling a method), will not compile if I remove the scoping around the if statement. See below:
publicclass Main{
publicstaticvoid main(String[] args){
finalboolean myBoolean = args.length > 1;
if (myBoolean)
finaldouble result = doIt();
}
publicstaticdouble doIt(){
return System.currentTimeMillis();
}
}
This fails to compile with the message:
Main.java:8: illegal start of expression
final double result = doIt();
Since the code is perfectly valid (as far as I'm aware), I was hoping someone might have an explanation for this strange behaviour. Oh, it fails to compile on 1.4 and 1.5 compilers.
The only thing I can think of is that the compiler is being clever and knows the declaration is stupid since the variable is never used. However, this doesn't explain why adding the scoping around the statement allows the code to compile. FYI, this is not limited to if statements. Also happens with for loops. Must be the single line scoping issue.
Thanks in advance,
Adam

