Question 7
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
public class Main {
static class TreeNode {
final int key;
final TreeNode left;
TreeNode right;
TreeNode(int key) { this.key = key; }
}
public static void main(String[] args) {
TreeNode root = new TreeNode(10);
root.right = new TreeNode(20);
System.out.println(root.key + root.right.key);
}
}
- A right must also be final
- B The final field left is never assigned in the constructor; every final field must be definitely assigned – drop final or assign it Correct
- C key cannot be final
- D TreeNode needs a toString method
Correct Answer: Option B
javac: "variable left might not have been initialized". Child links change as a tree grows, so they are normally not final.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!