Bird
0
0

Identify the error in the following Java code:

medium📝 Debug Q7 of 15
Java - Static Keyword
Identify the error in the following Java code:
class Sample {
    int number = 5;

    static void printNumber() {
        System.out.println(number);
    }

    public static void main(String[] args) {
        printNumber();
    }
}
AStatic method cannot access non-static variable 'number' directly
BMissing return type for method printNumber
CVariable 'number' should be declared static
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Check method and variable types

    printNumber() is static, number is non-static.
  2. Step 2: Understand access rules

    Static methods cannot directly access instance variables because they belong to the class, not an object.
  3. Step 3: Identify the error

    Trying to print number inside a static method causes a compile-time error.
  4. Final Answer:

    Static method cannot access non-static variable 'number' directly -> Option A
  5. Quick Check:

    Static methods lack instance context [OK]
Quick Trick: Static methods can't use instance variables without object [OK]
Common Mistakes:
  • Assuming static methods can access instance variables
  • Thinking variable must be static to fix error
  • Ignoring that static context lacks 'this'

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes