Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q6 of 15
Java - Static Keyword
Identify the error in this code snippet:
class Example {
    static void display() {
        System.out.println(message);
    }

    String message = "Hello";

    public static void main(String[] args) {
        display();
    }
}
AMissing return type for display method.
BCannot access non-static variable 'message' from static method.
CStatic method cannot be called from main.
DNo error, code runs fine.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze static method access

    Static methods cannot directly access non-static instance variables.
  2. Step 2: Identify the error

    display() tries to print 'message' which is non-static, causing a compile error.
  3. Final Answer:

    Cannot access non-static variable 'message' from static method. -> Option B
  4. Quick Check:

    Static method can't access instance variables directly [OK]
Quick Trick: Static methods can't access instance variables directly [OK]
Common Mistakes:
  • Assuming static methods can access instance variables
  • Ignoring compile-time errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes