0

Would anyone know why I am getting the error Variable 'tree' might not have been initialized

my method

public static TreeNode randomBST(TreeNode[] nodeArr) {
        TreeNode root = nodeArr[0];
        TreeNode tree;
        for (int i = 1; i < nodeArr.length; i++) {
            tree = buildBST(root, nodeArr[i]);
        }
        return tree;
    }

my buildBST method returns a TreeNode object.

I can fix this error by by assigning tree = null. How come I have to do this but if I were to initialize an int I dont have to? Is it because int is able to allocate a known amount of memory, where as the tree object is unknown amount of memory allocated?

Liondancer
  • 15,721
  • 51
  • 149
  • 255

1 Answers1

1

There's no guarantee to the compiler that the loop is ever entered. Thus the variable may not be initialized.

Chris Hayes
  • 11,471
  • 4
  • 32
  • 47