LearnFrenzy
Sign in Take a free test

Constructors and the this Keyword · Find the Error · Question 5

Error: assigning a final field twice Answer, explanation & discussion

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

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

Main.java
class Order {
    private final String id = "NEW";

    Order(String id) {
        this.id = id;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new Order("A1") != null);
    }
}
  • A id must be static
  • B id already has an initialiser, so a final field cannot be assigned again in the constructor Correct
  • C String cannot be final
  • D this cannot be used with final
Correct Answer: Option B

Remove "= NEW" and assign it only in the constructor.

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