Bird
0
0

Examine the following Java class and identify the error:

medium📝 Debug Q6 of 15
Java - Constructors

Examine the following Java class and identify the error:

class Employee {
  String name;
  int id;
  Employee(String name, int id) {
    this.name = name;
    this.id = id;
  }
  Employee() {
    name = "Unknown";
  }
}
public class Test {
  public static void main(String[] args) {
    Employee e = new Employee();
    System.out.println(e.id);
  }
}
AThe default constructor does not initialize 'id', so it prints 0
BThe parameterized constructor is missing the 'public' keyword
CThe class Employee lacks a constructor with no parameters
DThe code will not compile due to missing semicolons
Step-by-Step Solution
Solution:
  1. Step 1: Analyze constructors

    Employee has a parameterized and a default constructor; default sets name but not id.
  2. Step 2: Check main method output

    Creating Employee with default constructor sets name to "Unknown" but id remains default 0.
  3. Final Answer:

    The default constructor does not initialize 'id', so it prints 0 -> Option A
  4. Quick Check:

    Uninitialized int fields default to 0 in Java [OK]
Quick Trick: Uninitialized int fields default to 0 in Java [OK]
Common Mistakes:
  • Assuming uninitialized int fields have garbage values
  • Thinking missing 'public' causes error in constructors
  • Confusing compilation errors with runtime behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes