Stage 2: Object-oriented programming, lesson 2 of 10

static, final and constants

Beginner3 min read@since 9Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

static members belong to the class rather than to any one object:

  • static fields are shared by every instance (a counter, a cache, a constant).
  • static methods are called on the class, like Math.max(a, b). They can't use this or instance fields.
  • A static block runs once, when the class is loaded.

final means "assigned once":

  • A final variable can't be reassigned (the object it points to can still change).
  • A final method can't be overridden.
  • A final class can't be extended; String is final.

Constants combine both: public static final int MAX_SEATS = 60;, named in UPPER_SNAKE_CASE.

Use static for stateless helpers and constants. Avoid mutable static state: every thread and every test shares it, which makes bugs hard to find.

Example

Java
public final class Pricing {                     // final: can't be subclassed
    public static final double GST_RATE = 0.18;   // constant
    private static int quotes = 0;                // shared counter

    private Pricing() {}                          // utility class: no instances

    public static double withGst(double price) {
        quotes++;
        return price * (1 + GST_RATE);
    }

    public static int quotesGiven() { return quotes; }
}

double total = Pricing.withGst(1000);            // called on the class

final List<String> names = new ArrayList<>();
names.add("Asha");                               // allowed: the list itself changes
// names = new ArrayList<>();                    // compile error: can't reassign

Common mistake

Thinking a final reference makes the object immutable. A final List still lets you add and remove items; use List.copyOf for an unmodifiable list.

Under the hood

Static fields are initialised when the class is first used, and class initialisation is thread-safe, which is why the holder-class singleton works. final fields also get memory-model guarantees: once a constructor finishes, other threads see their values without synchronization. Local variables used in lambdas must be final or effectively final.

Check yourself

What does a final class prevent?

How this connects

Part of Java from zero.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.