Search code examples
javadead-code

Java Dead Code, can someone explain?


This is part of a binary tree class, here is the find function, given the key to find the node in the tree, if not found return null, however this part have been recognized as dead code, when I move the if(current==null) statement to the bottom of inside while loop, it works, why? is it the same?

public class Tree {
    public Node root;

    public Node find(int key) {
        Node current = root;
        while (current.key != key) {
            if (current == null) { //dead code here, why?
                return null;
            }

            if (key < current.key) {
                current = current.leftChild;
            } else if (key > current.key) {
                current = current.rightChild;
            }
        }
        return current;
    }
}

public class Node {
    public char label;
    public boolean visited = false;
    public int key;
    public float data;

    public Node leftChild;
    public Node rightChild;

}

Solution

  • If current is null it will never reach to the null check as you are accessing current.key beforehand it will throw a nullPointerException If you move the if(current==null) to bottom as you are assigning new value before it won't be a dead code. (as the current.leftChild and current.rightChild might be null)