Let’s break down static
in Java in the simplest possible way, step by step, and include examples to help you fully understand.
✅ What Does static
Mean in Java?
Think of static
as meaning “belongs to the class, not to objects”.
In Java, you can write code that either:
- Belongs to each individual object (like someone’s name or age), or
- Belongs to the class itself, shared by all objects (like a common rule or counter). That’s where
static
comes in.
🎯 Real-Life Analogy
Imagine a Car class:
- Each car object has its own color and speed (different for each car).
- But all cars share the same rule: they drive on the same road or follow the same speed limit.
We can say:
color
andspeed
are non-static (belong to each car).roadType
orspeedLimit
is static (shared by all cars, belongs to the class).
In Java Terms
👉 1. Static Variables (a.k.a Class Variables)
public class Car {
// static variable - shared by all Car objects
static int numberOfCars = 0;
// instance variable - each car has its own
String color;
public Car(String color) {
this.color = color;
numberOfCars++; // Increase count when a new Car is made
}
public void display() {
System.out.println("Color: " + color);
System.out.println("Total Cars: " + numberOfCars);
}
}
Usage:
public class Main {
public static void main(String[] args) {
Car c1 = new Car("Red");
Car c2 = new Car("Blue");
c1.display();
c2.display();
// Output:
// Color: Red, Total Cars: 2
// Color: Blue, Total Cars: 2
}
}
✔️ numberOfCars
is static — it’s shared and keeps track of all cars.
👉 2. Static Methods
Static methods are methods that belong to the class, not objects. You don’t need to create an object to use them.
public class MathUtil {
public static int add(int a, int b) {
return a + b;
}
}
Usage:
public class Main {
public static void main(String[] args) {
int result = MathUtil.add(5, 3);
System.out.println("Result: " + result); // Output: 8
}
}
✔️ You didn’t need to write new MathUtil()
— because add()
is static.
👉 3. Static Blocks
Static blocks are used to initialize static data. It runs once when the class is loaded.
public class Demo {
static int x;
static {
x = 10;
System.out.println("Static block executed");
}
}
👉 4. Static Classes (Nested)
You can make a static inner class (a class inside another class that doesn’t need an outer object).
public class Outer {
static class Inner {
public void show() {
System.out.println("Inside static inner class");
}
}
}
Usage:
public class Main {
public static void main(String[] args) {
Outer.Inner obj = new Outer.Inner();
obj.show();
}
}
🧠 Summary Table
Feature | static | Non-static |
---|---|---|
Belongs to | Class | Object |
Accessed using | ClassName.member | object.member |
Memory usage | One copy shared by all | Each object has its own |
Example use | Utility methods, counters | Personal data like name |