JAVA BASICS IN DETAIL

Java static keyword

static keyword ( static keyword) means that a field, method, block or nested class belongs to the class itself rather than an individual object. Such a member is shared by the class and often needs no object to access it.

A class or a specific object?

Differences between static and instance members
Propertystatic memberInstance member
What does it belong to?The classA specific object
How many values?One value shared by the classEach object has its own value
How is it accessed?Preferably through the class nameThrough an object reference
What is it suitable for?Constants, shared counters and utility methodsA specific object's state and behavior

1. A static field: one shared value

class Lankytojas {
    String vardas;
    static int sukurtuObjektu = 0;

    Lankytojas(String vardas) {
        this.vardas = vardas;
        sukurtuObjektu++;
    }
}

Lankytojas pirmas = new Lankytojas("Ieva");
Lankytojas antras = new Lankytojas("Mantas");

System.out.println(pirmas.vardas);
System.out.println(antras.vardas);
System.out.println(Lankytojas.sukurtuObjektu);
Console output

Ieva
Mantas
2

  1. Each Lankytojas object has its own field vardas.
  2. sukurtuObjektu is marked static, so the whole class shares one counter.
  3. Each constructor call increments the same shared value.
  4. We read the static field through the class: Lankytojas.sukurtuObjektu.

2. A static method: an action needs no object

class Temperaturos {
    static double iFarenheita(double celsijai) {
        return celsijai * 9 / 5 + 32;
    }
}

double rezultatas = Temperaturos.iFarenheita(20);
System.out.println(rezultatas);
Console output

68.0

The calculation uses only the supplied parameter and requires no specific Temperaturos object state. It therefore makes sense to mark it static and call it through the class.

Why can't a static method see object fields directly?

class Pirkejas {
    String vardas = "Rūta";

    static void rodytiVarda() {
        // Error: vardas belongs to a specific object
        System.out.println(vardas);
    }
}
Result

The code does not compile. A static method can be called without creating any Pirkejas object, so Java does not know which customer's name to display.

If a static method needs object data, pass the object explicitly:

class Pirkejas {
    String vardas;

    Pirkejas(String vardas) {
        this.vardas = vardas;
    }

    static void rodytiVarda(Pirkejas pirkejas) {
        System.out.println(pirkejas.vardas);
    }
}

Pirkejas pirkejas = new Pirkejas("Rūta");
Pirkejas.rodytiVarda(pirkejas);
Console output

Rūta

For the same reason, a static context cannot use this or super: there is no current object.

Call through a class or an object?

class Skaiciuotuvas {
    static int dvigubinti(int skaicius) {
        return skaicius * 2;
    }
}

Skaiciuotuvas objektas = new Skaiciuotuvas();

System.out.println(Skaiciuotuvas.dvigubinti(5)); // Recommended
System.out.println(objektas.dvigubinti(5));      // Works, but is misleading
Console output

10
10

Both forms compile, but objektas.dvigubinti(5) misleadingly suggests that a particular object's state is used. Write Skaiciuotuvas.dvigubinti(5) to make the method's class ownership immediately clear.

3. A static initializer block

class Nustatymai {
    static String valiuta;
    static int pristatymoDienos;

    static {
        System.out.println("Įkeliami nustatymai");
        valiuta = "EUR";
        pristatymoDienos = 3;
    }
}

System.out.println(Nustatymai.valiuta);
System.out.println(Nustatymai.pristatymoDienos);
Console output

Įkeliami nustatymai
EUR
3

  1. A static block runs once when the class is initialized.
  2. It runs before the first active use of static fields.
  3. The block suits more complex static-field initialization that is awkward to write as one expression.
Use sparingly.

Hidden file, network or database operations in a static block make testing and error handling harder. Simple constants usually need only direct assignment.

static final constants

class MatavimoVienetai {
    static final int MINUCIU_PER_VALANDA = 60;
    static final int SEKUNDZIU_PER_MINUTE = 60;
}

int sekundziu = 2
    * MatavimoVienetai.MINUCIU_PER_VALANDA
    * MatavimoVienetai.SEKUNDZIU_PER_MINUTE;

System.out.println(sekundziu);
Console output

7200

static means the value belongs to the class, while final means the reference or primitive value cannot be reassigned. Constant names conventionally use uppercase letters with underscores.

4. A static nested class

class Adresas {
    static class Tikrintuvas {
        boolean tinkamasPastoKodas(String kodas) {
            return kodas != null && kodas.length() == 5;
        }
    }
}

Adresas.Tikrintuvas tikrintuvas = new Adresas.Tikrintuvas();
System.out.println(tikrintuvas.tinkamasPastoKodas("01100"));
Console output

true

Adresas.Tikrintuvas logically belongs to the Adresas concept, but its instance needs no enclosing Adresas object. static can apply to a nested class, but not an ordinary top-level class.

Why is main() static?

The Java virtual machine must start the program before any instance of your class exists. It can therefore call the class method directly:

public static void main(String[] args)

If main() were not static, an object would be needed first, but there would be no method yet to create it at program startup.

Static methods are not overridden

If a subclass defines a static method with the same signature, it hidesthe parent method rather than overriding it. Selection depends on the reference type or class name, not the actual object.

More about static method hiding and method overriding

When should you use or avoid static?

Choosing static in practice
A good choiceUse caution
Immutable shared constantsMutable global state
Pure utility calculationsData that actually belongs to an object
Clear object countersShared state across threads without synchronization
Factory methodsDependencies that tests need to replace

A mutable static field acts as shared program state. Many objects can change it, making it harder to track who changed a value and when. A multithreaded environment also requires safe access.

What should you remember?

  • static member belongs to the class, not a specific object.
  • Access static fields and methods through the class name.
  • A static field is shared by all instances of that class.
  • A static method cannot directly access instance fields or use this or super.
  • A static block runs once when the class is initialized.
  • static final is often used for shared constants.
  • Only nested classes can be static, not top-level classes.
  • Use mutable shared static state carefully.