Eclipse keep stating that the last elseif and the else is dead code but I don't get it.
if (img0 != null && img1 != null) {
code;
} else if (img0 != null) {
code;
} else if (img1 != null) {
code;
} else {
code;
}
I reason like this:
What am I missing, where is the "deadness"?
Thanks in advance.
Take a look at the use of your code in these two ways: -
public static void main(String[] args)
{
String img0 = null;
String img1 = "Asdf";
/** Currently there is no code here, that can modify the value of
`img0` and `img1` and Compiler is sure about that.
**/
/** So, it's sure that the below conditions will always execute in a
certain execution order. And hence it will show `Dead Code` warning in
either of the blocks depending upon the values.
**/
if (img0 != null && img1 != null) {
// code;
} else if (img0 != null) {
//code;
} else if (img1 != null) {
//code;
} else {
// code;
}
}
In this case, you would certainly get dead code
warning on one block or the other, because you are setting the value just before the blocks, and the compiler is sure that the values won't change between the initialization and execution of those blocks.
public static void main(String[] args)
{
String img0 = null;
String img1 = "Asdf";
show(img0, img1);
}
public static void show(String img0, String img1) {
/** Now here, compiler cannot decide on the execution order,
as `img0` and `img1` can have any values depending upon where
this method was called from. And hence it cannot give dead code warning.
**/
if (img0 != null && img1 != null) {
// code;
} else if (img0 != null) {
//code;
} else if (img1 != null) {
//code;
} else {
// code;
}
}
Now, in this case, you won't get dead code
warnings, because Compiler is not sure, from where the show
method might get invoked. Values of img0
and img1
can be anything inside the method.
null
, the last else
will be executed.one of them is null
, one of the else if
will be executed.null
, your if
will be executed.Note : -
If you want, you can configure Eclipse not to show warnings
for certain cases like - Unneccessary else
, Unused Imports
, etc.
Go to Windows -> Preferences -> Java (on Left Panel) -> Compiler -> Errors/ Warnings
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With