Bird
0
0

Identify the error in the following Java code snippet:

medium📝 Debug Q6 of 15
Java - Constructors
Identify the error in the following Java code snippet:
class Box {
  int length;
  Box() {
    this(5);
  }
  Box(int length) {
    length = length;
  }
}
AThe constructor call this(5) must be the first statement
BMissing return type in constructors
CCannot overload constructors in Java
DThe assignment length = length does not assign the parameter to the instance variable
Step-by-Step Solution
Solution:
  1. Step 1: Analyze constructor chaining

    The call this(5); is correctly placed as the first statement in the no-arg constructor.
  2. Step 2: Check variable assignment

    In Box(int length), the assignment length = length; assigns the parameter to itself, not to the instance variable.
  3. Step 3: Correct assignment

    Use this.length = length; to assign the parameter to the instance variable.
  4. Final Answer:

    The assignment length = length does not assign the parameter to the instance variable -> Option D
  5. Quick Check:

    Use this.variable to assign parameter to instance variable [OK]
Quick Trick: Use this.var to assign parameter to instance variable [OK]
Common Mistakes:
  • Assuming length=length assigns instance variable
  • Thinking constructor chaining is incorrect here
  • Confusing constructor with method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes