What is the static keyword?
Solution and explanation
What it is
static marks a member as belonging to the class itself rather than to individual objects. There is one copy shared by all instances, and it can be used without creating an object.
Where static can be used
| Usage | Meaning |
|---|---|
| Static variable | One shared copy for the class |
| Static method | Called on the class; no this |
| Static block | Runs once when the class is initialised |
| Static nested class | Nested class that does not need an outer instance |
| Static import | Use static members without the class name (import static java.lang.Math.*;) |
Example
public class Order {
private static int totalOrders = 0; // shared counter
private static final double GST = 0.18; // shared constant
private final int orderNo;
static { System.out.println("Order class loaded"); } // static block
public Order() { orderNo = ++totalOrders; }
public static int getTotalOrders() { return totalOrders; } // static method
public static double withGst(double amount) { return amount * (1 + GST); }
}
new Order(); new Order();
System.out.println(Order.getTotalOrders()); // 2
System.out.println(Order.withGst(1000)); // 1180.0
Rules
- Static methods cannot use
thisorsuperand cannot access instance members directly. - Static methods are not overridden (they are hidden).
- Top-level classes cannot be static; only nested classes can.
- Local variables cannot be static.
When to use
Constants, counters, utility/helper functions (Math.sqrt, Collections.sort), factory methods (List.of). Avoid mutable static state in multi-threaded or testable code: it is effectively a global variable.
