Can we call a non-static variable in static method?

No, a static method cannot directly access non-static variables or methods—because static methods belong to the class, while non-static members belong to an instance (object) of that class.

🧠 Why This Happens:

  • A static method can be called without creating an object.
  • A non-static variable exists only after an object is created.
  • So, if you try to access a non-static variable from a static method, the compiler will complain:
    “Non-static variable cannot be referenced from a static context.”

✅ How to Access It Anyway?

You can create an object and then use it to access the non-static variable:

public class MyClass {
int count = 5; // non-static variable

public static void main(String[] args) {
    MyClass obj = new MyClass();         // ✅ create an object
    System.out.println(obj.count);       // access non-static variable
}

}

Leave a Reply

Your email address will not be published. Required fields are marked *