Take a look at the use of your code in these two ways: -
Way 1: -
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.
Way 2: -
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.
- In case both of them are
null
, the last else
will be executed.
- In case
one of them is null
, one of the else if
will be executed.
- And, in case none of them are
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