Search code examples
javadead-code

Why do I get warning "dead code"?


public class DeadCodeInLuna {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String string;
        for (string = in.readLine(); !string.equals(""); string=in.readLine()) {
            if(string == null) { 
               System.out.println("null while reading response!");
            }
        }
    }
}

Solution

  • Because string can never be null if !string.equals("") evaluates to true.

    In other words, when !string.equals("") is true, string is guaranteed to be not null otherwise a NullPointerException would have occurred.