Unreachable code removal

When a block of code is unreachable at compile time, will the compiler remove it? Example:

final boolean DO_THAT = false;

if (DO_THAT) {
// code…
}

In my application I’m specially interested in the removal of the condition check, since the condition will always be true or false at compile time.

dunno, but this can easily be checked out with a decompiler or by just examining the size of the class file.

I thought the compiler spec said something like that.
In any case, we have an static class called debug in one of our projects and it has a static final boolean.
Seems to work for us

Unreachable code is removed by the Java compiler but I think only if you specify -O with javac (“optimizing”). I think Eclipse and other IDEs always optimize.

Dynamically unreachable code is removed by the server Hotspot JVM too (ie. assertions and the like).

Cas :slight_smile:

[quote]When a block of code is unreachable at compile time, will the compiler remove it? Example:

final boolean DO_THAT = false;

if (DO_THAT) {
// code…
}
[/quote]
IIRC from the earlier thread about this, there are two scenarios:
1 - the final flag is in the same class. In this case, by definition, the compiler removes the relevant code.
2 - the final flag is in a different class; nothing happens (because the “other class” could be recoded and recompiled at any time, invalidating the assumption).

Basically, “final” has no meaning outside of the class file it’s defined in?

That was what I had thought, but apparently thats not the case. See here: http://www.java-gaming.org/cgi-bin/JGNetForums/YaBB.cgi?board=Tuning;action=display;num=1067092857;start=15

final static boolean foo = false;

if (foo) {
// this is removed
}

Thats been true by definition in Java since the very beginning, one of the reasons we don’t miss having a precompiler so much :slight_smile:

I forget why the static, if you really want me to I could dig into the manuals and figure it out.

It is indeed true about static finals - even when in other classes they will affect the compilation and throw out dead code. Good thing too or my Sys.DEBUG flag would be bugger all use!

Cas :slight_smile:

[quote]It is indeed true about static finals - even when in other classes they will affect the compilation and throw out dead code. Good thing too or my Sys.DEBUG flag would be bugger all use!

Cas :slight_smile:
[/quote]
…but what about non-static finals; is my question above correct, that an ordinary final doesn’t have relevance outside the class?

I’ll ask one of the compiler geeks…

[quote]I’ll ask one of the compiler experts…
[/quote]
good idea