DEV Community

levi
levi

Posted on • Edited on

JUST STATIC it: Understanding static in Java

DAY 5. I am trying to strength by Core java basic its one of the concepts I struggle to understand. here is everthing I learnt today about static keyword in java

Java Summary: Static, Class Loading & Execution Flow


1. static Keyword in Java

Definition:

The static keyword means the member belongs to the class itself, not to instances.

class CarFactory {
    // Static variable shared by all cars made by any factory
    static int totalCarsProduced = 0;

    // Static block: runs once when the class is loaded
    static {
        System.out.println("CarFactory class loaded. Initializing factory...");
    }

    // Instance variable (per car)
    String model;

    // Constructor increments total cars produced
    CarFactory(String model) {
        this.model = model;
        totalCarsProduced++;
    }

    // Static method: calculates price without needing an object
    static int calculatePrice(String model, int basePrice) {
        if ("Luxury".equalsIgnoreCase(model)) {
            return basePrice + 7000;
        } else {
            return basePrice;
        }
    }

    // Static nested class representing a part of the car
    static class Engine {
        void start() {
            System.out.println("Engine started.");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        // Class loaded, static block runs first

        // Create cars (instances)
        CarFactory car1 = new CarFactory("Standard");
        CarFactory car2 = new CarFactory("Luxury");

        // Access static variable shared by all cars
        System.out.println("Total cars produced: " + CarFactory.totalCarsProduced); // 2

        // Call static method without creating an object
        int price = CarFactory.calculatePrice("Luxury", 25000);
        System.out.println("Price of Luxury car: $" + price);  // 32000

        // Create and use static nested class (no CarFactory instance needed)
        CarFactory.Engine engine = new CarFactory.Engine();
        engine.start();
    }
}

Enter fullscreen mode Exit fullscreen mode

Where static Can Be Used:

  • Static variable → Shared among all instances (1 copy in memory)
  • Static method → Can be called without object creation; can't access instance members directly
  • Static block → Runs once when class is loaded; used to initialize static fields. they cant return anything.
  • Static nested class → Class inside another class; does NOT need outer class object

Static Nested Class vs Inner Class

Static Nested Class Inner (Non-Static) Class
Access only static members of outer class Can access all members of outer class
Does NOT require outer class instance Requires outer class instance
Can be instantiated independently Must be tied to an outer class object

Key Rules:

  • Static methods can't access instance fields or methods directly.
  • Static methods can't be abstract.
  • Static methods can't be overridden (they're hidden instead).
  • Static blocks and variables execute in order of appearance.

2. Class Loading & Initialization

What Is Class Loading?

Class loading is the process of bringing .class files into memory using a ClassLoader.

Class Loaders:

  1. Bootstrap ClassLoader – loads core Java classes (e.g., java.lang)
  2. Extension ClassLoader – loads JDK extensions
  3. Application ClassLoader – loads user-defined classes

What Gets Loaded:

  • Class structure (fields, methods, hierarchy)
  • Constant pool
  • Static fields (with default values first)
  • Method bytecode
  • Static blocks

Phases of Class Loading:

Phase Description
Loading Reads .class file into memory
Linking Verifies bytecode, allocates memory for statics
Initialization Assigns actual static values, runs static blocks

3. JVM Memory Areas

Memory Area What it Stores
Method Area Class metadata, static variables, constant pool
Heap Objects and instance variables
Stack Method calls and local variables (per thread)
PC Register Instruction pointer per thread
Native Method Stack Native (non-Java) method calls

4. Java Program Execution Flow

Steps When Running a Program

  1. Class is loaded
  2. Static variables are initialized
  3. Static blocks execute (in order)
  4. main() method is called
  5. If object is created:
    • Instance variables init
    • Instance block runs
  6. Constructor runs

5. Final vs Static

we will cover final in depth another article.
any member declared as:

Feature static final
Belongs to Class Class or instance
Overriding Static methods cannot be overridden (hidden) Final methods cannot be overridden
Inheritance N/A (related to members) Final class cannot be extended
Usage Share common data, utility methods, nested classes Prevent modification of method/class inheritance

6. Where You Cannot Use static in Java?

Usage Can you use static here? Reason
Local variables inside methods ❌ No Java does not allow static local variables
Constructors ❌ No Constructors are always instance-level
Abstract methods ❌ No static and abstract are contradictory
Interfaces (before Java 8) ❌ No But Java 8+ allows static methods inside interfaces

Top comments (0)