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?
| Property | static member | Instance member |
|---|---|---|
| What does it belong to? | The class | A specific object |
| How many values? | One value shared by the class | Each object has its own value |
| How is it accessed? | Preferably through the class name | Through an object reference |
| What is it suitable for? | Constants, shared counters and utility methods | A 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);Ieva
Mantas
2
- Each
Lankytojasobject has its own fieldvardas. sukurtuObjektuis markedstatic, so the whole class shares one counter.- Each constructor call increments the same shared value.
- 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);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);
}
}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);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 misleading10
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);Įkeliami nustatymai
EUR
3
- A static block runs once when the class is initialized.
- It runs before the first active use of static fields.
- The block suits more complex static-field initialization that is awkward to write as one expression.
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);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"));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.
When should you use or avoid static?
| A good choice | Use caution |
|---|---|
| Immutable shared constants | Mutable global state |
| Pure utility calculations | Data that actually belongs to an object |
| Clear object counters | Shared state across threads without synchronization |
| Factory methods | Dependencies 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?
staticmember 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
thisorsuper. - A static block runs once when the class is initialized.
static finalis often used for shared constants.- Only nested classes can be static, not top-level classes.
- Use mutable shared static state carefully.