I have a very simple Java code, like this (this is just an excerpt):
for(;;)
{
AnObject object = null;
for(AnObject elem : list) // where the list is of the type List<AnObject>
{
if(<some dynamic condition goes here>)
{
object = elem;
}
}
Log.v(TAG, object.property); // was initially omitted, added for the answer
// more code skipped for simplicity
if(object == null)
{ //
break; //
} // this all is marked as dead code
}
In Eclipse, the fragment with comments is marked as a dead code. Why? There is no final
elements in the condition. The object
variable is not assigned anywhere to constant null, except for the very beginning of the cycle, after which it should be normally overriden, but it does not happen always. The object
can very well be null and non-null.
Am I missing something?
The Answer
Well, I found the answer, and to show it I must add one line of code to my example, which I omitted by accident when tried to simplify the code excerpt, but it is important. The line is:
Log.v(TAG, object.property);
So the object must be non-null, otherwise the code unreachable by exception. This line was added temporary for debugging purposes, which is why it was out of my consideration.
I can't reproduce that warning in eclipse.
Could it be that you accidently forgot some piece of code in your original question which might lead to a situation where no code behind it is executed. As you marked the complete if
statement as dead code and not just its body, this seems to be the case. That missing line could be something that actually uses object
(probably as simple as a logging statement where you try to access one of object
's properties).
Even if the if
condition is not marked as dead, its body might still be. Either object
is not null
(and the if
body would not be executed) or – if object
is null – a NullPointerException
would be thrown in that missing line so that the execution stops there.