static, final and constants
static members belong to the class rather than to any one object:
staticfields are shared by every instance (a counter, a cache, a constant).staticmethods are called on the class, likeMath.max(a, b). They can't usethisor instance fields.- A
staticblock runs once, when the class is loaded.
final means "assigned once":
- A
finalvariable can't be reassigned (the object it points to can still change). - A
finalmethod can't be overridden. - A
finalclass can't be extended;Stringis 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
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 reassignCommon 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
Know these first
Where this leads
Part of Java from zero.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.