Bird
0
0

Identify the error in the following code snippet:

medium📝 Debug Q14 of 15
Java - Static Keyword
Identify the error in the following code snippet:
class Counter {
    static int count;
    void increment() {
        count++;
    }
    public static void main(String[] args) {
        Counter c = new Counter();
        c.increment();
        System.out.println(count);
    }
}
ACannot access static variable from instance method.
BNo error; code runs and prints 1.
CCannot access static variable directly in static method without class name.
DStatic variable count is not initialized.
Step-by-Step Solution
Solution:
  1. Step 1: Check static variable initialization

    Static int variables default to 0 if not explicitly initialized.
  2. Step 2: Verify method calls and access

    The instance method increment() correctly increments the static variable. The static method main accesses count directly, which is allowed.
  3. Final Answer:

    No error; code runs and prints 1. -> Option B
  4. Quick Check:

    Static variable accessible and increments correctly [OK]
Quick Trick: Static vars default to 0; accessible in static main [OK]
Common Mistakes:
  • Thinking static vars must be explicitly initialized
  • Assuming static vars can't be accessed without class name inside same class
  • Confusing instance and static method access rules

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes