Going through some old code written by one of my teammate, I found this really strange code:
if (...) {
// some code
} else if (this == null) {
System.out.println("I expected this to be dead code!");
}
Strange isn't it. AFAIK, this == null
condition can never be true
, which should be obvious to the compiler, as it knows the meaning of this
and null
both. But to my surprise, that wasn't marked as dead code.
I tried this code both in Eclipse, and through command line. I ran the following command to enable all warning:
javac -Xlint:all MyClass.java
Still it didn't gave any warning.
On contrary, if I change the else if
block to:
else if (false) {
System.out.println("As expected, this is dead code");
}
The statement inside was marked as dead code, as I expected.
So why this behaviour? This only leads me to think that there might be some condition where this
can actually be null
. Is it?
The JLS has a definition of unreachable code:
The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.
So this is not considered "unreachable".
Also see this discussion about unreachable code errors and dead code warnings.