Search code examples
javaif-statementdead-code

the code in my else statement is dead and I don't believe it is true (java)?


I am working with an organized BST in my java code. This function/method is supposed to search the tree for a node with a specific value and let the user know whether or not it exists.

    void search(int item, Node root, int r, int c) {

        //if the integer is found
        if(root.val == item) {
            System.out.println("integer located at row: " + r + " & child: " + c + "\n");
        }

        //if the integer is not found (use the closest value to find it)
        else if(root != null) {
            if(item < root.val) 
                search(item, root.left, r + 1, (c * 2) - 1);
            else
                search(item, root.right, r + 1, c * 2);
        }

        //if the root is a null (it doesn't exist or cannot be found)
        else {
            System.out.println("integer cannot be located\n");
        }
    }

The problem is the else statement at the end. My compiler says that anything in that else statement is dead code, meaning it isn't used. However, I need the code in that else statement in the event that the function does encounter a null and cannot find the node with the assigned value. It goes away if I change the second else statement to else if(root.val != item && root != null) but it leaves me to wonder if there is a point where root won't equal null I know that it should be a possibility. Is the else statement really dead code and if it is, how can I change that?


Solution

  • Your first if expression:

    if (root.val == item)
    

    will either throw a NullPointerException if root is null or perform the comparison if not. Hence the final else block can never be executed.

    You could try re-ordering your code:

    void search(int item, Node root, int r, int c) {
        if (root != null) {
           if (root.val == item) {
               System.out.println("integer located at row: " + r + " & child: " + c + "\n");
           } else if (item < root.val) {
                search(item, root.left, r + 1, (c * 2) - 1);
           } else {
                search(item, root.right, r + 1, c * 2);
           }
        } else {
           System.out.println("integer cannot be located\n");
        }
     }