LearnFrenzy
Sign in Take a free test

Data Structures in Java · Data Structures in Java – Find the Error · Question 7

Error: a final child field never assigned Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links