cssGEEK cssGEEK - 5 months ago 15
Java Question

dead code warning java

I have the following part of code:

public void deepSearch(File fileToLook,ArrayList<File> fileStorage,DefaultComboBoxModel<String> mod){
if(fileToLook.isDirectory())
{
for(File f:fileToLook.listFiles())
deepSearch(f,fileStorage,mod);
}
else if(fileToLook != null){
fileStorage.add(fileToLook);
mod.addElement(fileToLook.getName());
}
else
System.out.println("Reached an end.");
}


But eclipse gives me a dead code warning on this:

else
System.out.println("Reached an end.");


Can you explain why this is happening.Thanks in advance

Answer

Well, fileToLook can't be null when the else statement is reached, since if it is null, the first condition will throw a NullPointerException.

It would make more sense to refactor the method, and avoid the potential NullPointerException :

if(fileToLook != null) {
    if(fileToLook.isDirectory()) {
        for(File f:fileToLook.listFiles())
            deepSearch(f,fileStorage,mod);
    } else {
        fileStorage.add(fileToLook);
        mod.addElement(fileToLook.getName());
    }
} else {
    System.out.println("Reached an end."); // not sure if you really need this
                                           // statement. It looks like a debug print to me
}
Comments