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

[2881 byte] By [threadSavera] at [2007-10-2 15:24:40]
# 1
Remove the "final" keyword.
MartinHilperta at 2007-7-13 14:38:49 > top of Java-index,Developer Tools,Java Compiler...
# 2

Thank you so much for your insightful and considered suggestion. I hope I don't shock you too much by telling you that I have in fact tried it without the final keyword. Regardless of whether or not this gets around the compilation issue (it doesn't - did you even try it?), the question in my original post was fairly clearly along the lines of "Does anyone know why this compiles with the braces, and doesn't compile without them?"

Does anyone have anything useful to contribute?

threadSavera at 2007-7-13 14:38:49 > top of Java-index,Developer Tools,Java Compiler...
# 3

See the Java grammar. The language element following 'if' or 'else' (or 'while' or 'do') is a statement. The line you have is not a statement, it is a declaration. However a block delimited by {} is a statement (which in turn can contain both declarations and statements).

Most block-structured languages behave this way, in fact all the ones I know.

ejpa at 2007-7-13 14:38:49 > top of Java-index,Developer Tools,Java Compiler...
# 4
Many thanks ejp. You know, that actually makes sense.All the best
threadSavera at 2007-7-13 14:38:49 > top of Java-index,Developer Tools,Java Compiler...