Skip to content

Beginner · Classes and objects · topic 19 of 60 · 20 min

static members and final

Explanation

static fields and methods belong to the class, not to any one object: one shared copy for everyone, used as ClassName.member. They suit counters, constants and utility methods like Math.max. final means "assigned once": final variables become constants, final methods cannot be overridden, and final classes cannot be extended.

static fields: one copy for the whole class

java
public class Ticket {
    private static int issued = 0;      // shared by ALL tickets
    private final int number;           // each ticket has its own

    public Ticket() {
        issued++;
        number = issued;
    }
    public int getNumber() { return number; }
    public static int getIssued() { return issued; }   // static method
}
new Ticket(); new Ticket(); Ticket t3 = new Ticket();
System.out.println(t3.getNumber());      // 3
System.out.println(Ticket.getIssued());  // 3 (called on the class)

static methods

A static method does not run on an object, so it has no this and cannot use instance fields directly. It is ideal for utility functions that only need their parameters: Math.sqrt, Integer.parseInt, Arrays.sort. That is also why main is static: the JVM can call it before any object exists.

java
public final class GstUtil {
    private GstUtil() {}                                // no objects of a utility class
    public static final double STANDARD_RATE = 18.0;   // a constant
    public static double withGst(double amount) {
        return amount * (1 + STANDARD_RATE / 100);
    }
}
double total = GstUtil.withGst(1000);   // 1180.0
Careful: A static method cannot use instance fields or call instance methods without an object: in public static void main, writing balance = 5; or show(); for instance members gives "non-static variable balance cannot be referenced from a static context". Either create an object first (new Account().show()) or make the member static if it truly belongs to the class.

Constants: public static final

A constant is a value that never changes and is the same for everyone: public static final int MAX_LOGIN_ATTEMPTS = 3;. Name constants in UPPER_SNAKE_CASE. For a group of related constants (payment modes, order statuses), an enum is usually better.

final in three places

WhereMeaningExample
final variable / fieldCan be assigned only oncefinal String owner;
final methodSubclasses cannot override itpublic final void audit()
final classNo class can extend itpublic final class String

final on a reference variable means the variable cannot point to another object, NOT that the object cannot change: final List<String> list = new ArrayList<>(); list.add("x"); is fine.

static blocks (in brief)

A static { … } block runs once when the class is first loaded, for complex static initialisation such as loading a table of rates. Use it sparingly.

Think of it like this: In a school, each student has their own roll number (instance field), but the school's name and the total number of students enrolled belong to the school as a whole (static fields). The notice board in the corridor (a static method) does not belong to any single student.
Tip: Too many static fields that change (mutable global state) make programs hard to test and unsafe with threads. Use static mainly for constants and pure utility methods.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

static members and final · 1/6

static and final

In this lesson you will learn what static and final mean.

Prefer a video by a teacher? Find free videos on “java static keyword final keyword explained” on YouTube ↗

In real life: Invoice numbers for a shop

A billing app numbers invoices INV-0001, INV-0002… A static counter in the Invoice class is shared by every invoice object, so each new invoice gets the next number. (In a real multi-user system the number would come from the database.)

java
public class Invoice {
    private static int counter = 0;
    private final String number;
    public Invoice() { counter++; number = String.format("INV-%04d", counter); }
    public String getNumber() { return number; }
}
// new Invoice().getNumber() → "INV-0001", the next one → "INV-0002"

Practice (0/3 done)

Task 1 · Question

What does this print? class C { static int s = 0; int i = 0; C() { s++; i++; } } … new C(); new C(); C c = new C(); System.out.println(C.s + " " + c.i);

Task 2 · Question

Which line gives "non-static method show() cannot be referenced from a static context"? class App { void show() {} public static void main(String[] a) { show(); // line X new App().show(); // line Y } }

Task 3 · Practice

Write a utility class TempUtil with a private constructor, a constant ABSOLUTE_ZERO_C = -273.15, and static methods cToF(double) and fToC(double). Call them from main without creating an object.

Quick quiz

Question 1

1.Why is main declared static?

Question 2

2.final List<String> list = new ArrayList<>(); list.add("a"); Does this compile?

Question 3

3.Which class is final in the JDK?

Question 4

4.How do you usually call a static method?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Why is main declared static?

Answer: So the JVM can call it without creating an object

No object exists when the program starts.

final List<String> list = new ArrayList<>(); list.add("a"); Does this compile?

Answer: Yes: final stops reassignment, not changes to the list

The reference is final; the object is still mutable.

Which class is final in the JDK?

Answer: String

String is final, so nobody can subclass it.

How do you usually call a static method?

Answer: ClassName.method()

Static members belong to the class.

Two objects of the same class…Related

Answer: Each have their own copies of instance fields

Instance fields belong to each object.

From Classes and objects

How do you call a static method Fare on class MetroCard?Related

Answer: MetroCard.Fare(3)

Static members are reached through the class name.

From Access modifiers, static members and encapsulation

A static member variable is…Related

Answer: shared by the whole class, one copy in total

Static members belong to the class, not to individual objects.

From Classes and objects: data plus behaviour

How is a static method called?Related

Answer: ClassName.method()

Static members belong to the class itself.

From Classes

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Classes and objects” before its exam: toString, equals, hashCode and records.
  2. Module 4 exam: Classes and objects · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Inheritance, polymorphism and interfaces. 60 topics left in the course before the final exam.

← Previous: Encapsulation: private fields, getters and setters