What is a static method and a static variable?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for OOP Concepts development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
Static members belong to the CLASS rather than any specific instance (object). All instances share the same static member, and static members exist even when no instances have been created. Static variable (class variable): class Student { private String name; private int grade; // Static -- shared by ALL Student instances: private static int totalStudents = 0; private static final int MAX_GRADE = 100; // Constant public Student(String name, int grade) { this.name = name; this.grade = Math.min(grade, MAX_GRADE); totalStudents++; // Increment shared counter } public static int getTotalStudents() { return totalStudents; } }. Static method (class method): belongs to the class; can only access other static members directly (no access to instance fields/this); called on the class, not an object: Student s1 = new Student("Alice", 90); Student s2 = new Student("Bob", 85); Student.getTotalStudents(); // 2 -- called on class // s1.getTotalStudents(); // Works but misleading -- don't do this. Common uses: utility/helper methods (Math.sqrt(), Collections.sort()); factory methods (getInstance()); constants (Math.PI); counters/registries shared across all instances; Singleton patterns. Static initializer block: static { // Runs once when class is first loaded totalStudents = loadFromDatabase(); }. Cannot: use this or super in static methods; override static methods (they are hidden, not overridden); access non-static members without an instance reference.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex OOP Concepts answers easy to follow.
Previous
What are access modifiers?
Next
What is the difference between stack and heap memory in OOP?