Search code examples
javadead-code

Why am I getting dead code warning here in java?


I'm getting dead code warning in eclipse from the if(line == null) statement to the r.close() statement.

BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));

int counter = 0;

while(true)
{
    String line = r.readLine();
    counter++;

    if(line.contains(" = "))
    {
        String[] keyVal = new String[2];

        keyVal[0] = line.substring(0, line.indexOf(" = ") - 1);
        keyVal[1] = line.substring(line.indexOf(" = ") + 3);

        buffer.add(keyVal);
    }
    else
    {
        new Exception("Invalid expression at line " + counter + " in file " + file.getPath()).printStackTrace();
    }

    if(line == null) // dead code here
    {
        break;
    }
}

System.out.println("here is a dead code");

r.close(); // another dead code

Solution

  • You are operating on line with if(line.contains(" = ")). If line was null, a NullPointerException would be thrown, which you are not catching. Therefore, the break; statement can't be reached. If the if(line == null) statement is reached, it's not null. Logically, break; will never be executed, so it's unreachable. It appears that Eclipse is detecting this. Note that this will still compile with javac just fine; this is just Eclipse's warning.

    Furthermore, if the break; is unreachable, then there is no way to end while(true), so anything beyond the while block is unreachable. So Eclipse warns on this too.

    The usual way of reading a file line-by-line, checking the line for null to indicate end of the stream, is

    String line;
    while ( (line = r.readLine() ) != null)
    {
        // rest of processing here
    }
    

    It's not the cleanest code, with an assignment in the same expression as an equality check, but it's the usual way of doing this kind of read-and-check operation.

    This way the while statement can end normally, and then there is no need to check for null later. That also makes any code following the while block reachable.