</>

Technology

Core Java

Difficulty

Beginner

Interview Question

What is the static keyword in Java? Explain static variables, methods, and blocks.

Answer

The static Keyword in Java

static means the member belongs to the class itself, not to any individual object.

1. Static Variable — Class-Level Variable

Shared across all instances of the class. One copy in memory regardless of how many objects are created.

Java
public class Employee {
    String name;           // instance variable — each object has its own
    static int count = 0;  // static variable — shared across all objects

    public Employee(String name) {
        this.name = name;
        count++;           // increments the shared counter
    }
}

Employee e1 = new Employee("Alice");
Employee e2 = new Employee("Bob");
Employee e3 = new Employee("Charlie");

System.out.println(Employee.count); // 3 — accessed via class name

2. Static Method — Class-Level Method

Can be called without creating an object. Cannot access instance (non-static) variables directly.

Java
public class MathUtils {
    public static int add(int a, int b) {
        return a + b;
    }

    public static double square(double n) {
        return n * n;
    }
}

// No object needed
int result = MathUtils.add(3, 4);      // 7
double sq  = MathUtils.square(5.0);   // 25.0

Restriction: Static methods CANNOT access this or non-static members directly.

Java
public class Example {
    int x = 10;  // instance variable

    public static void staticMethod() {
        // System.out.println(x);  // ❌ Compile error — x is instance variable
        System.out.println("Static method");
    }
}

3. Static Block — Class Initialization

Runs once when the class is first loaded into memory. Used for one-time initialization.

Java
public class DatabaseConfig {
    static String url;
    static String username;

    static {
        // Runs once when class loads
        url      = System.getenv("DB_URL");
        username = System.getenv("DB_USER");
        System.out.println("DB config loaded");
    }
}

4. Static Nested Class

A nested class declared static — can exist without an instance of the outer class.

Java
public class Outer {
    static class Inner {
        void display() { System.out.println("Static inner class"); }
    }
}

Outer.Inner obj = new Outer.Inner();  // no Outer instance needed

Static vs Instance

FeaturestaticInstance
Belongs toClassObject
MemoryOne copyPer-object copy
AccessClassName.memberobject.member
this keyword❌ Not available✅ Available

In Automation Frameworks

Java
public class DriverManager {
    private static WebDriver driver;  // one shared driver instance

    public static WebDriver getDriver() {
        if (driver == null) {
            driver = new ChromeDriver();
        }
        return driver;
    }
}

// Any test class can call without creating DriverManager object
WebDriver driver = DriverManager.getDriver();

Follow AutomateQA

Related Topics