Two small keywords appear in almost every Java program. static means “belongs to the class, not to any one object”: a counter shared by all students, or a helper method such as Math.max that needs no object. final means “cannot be changed”: a constant, a field set once in the constructor, a method that subclasses may not override. This lesson shows both with working examples and clears up the most common confusion about final objects.
In this lesson you will learn
- Static fields shared by every object
- Static methods and why they cannot use instance fields
- Static initialisation blocks
- Final variables, fields, methods and classes
- Constants with
static final
You should already know classes and objects.
Static Fields and Methods
public class Main {
static class Student {
static int count = 0; // shared by all Student objects
static final String SCHOOL = "Dhaka College";
final int id; // set once, never changed
String name;
Student(String name) {
count++;
this.id = count;
this.name = name;
}
static String schoolInfo() { // no object needed
return SCHOOL + " has " + count + " students";
}
}
public static void main(String[] args) {
System.out.println(Student.schoolInfo());
Student a = new Student("Nusrat");
Student b = new Student("Arif");
Student c = new Student("Tania");
System.out.println(a.name + " id=" + a.id + ", " + c.name + " id=" + c.id);
System.out.println(Student.schoolInfo());
System.out.println("Read through an object: " + b.count);
System.out.println("Math.max is static too: " + Math.max(7, 12));
}
}
Output
Dhaka College has 0 students
Nusrat id=1, Tania id=3
Dhaka College has 3 students
Read through an object: 3
Math.max is static too: 12
static int countexists once, for the wholeStudentclass. Each constructor call increases the same counter, so after three objects it is 3.nameandidare instance fields: every object has its own copy.Student.schoolInfo()is called on the class itself, even before any object exists, which is why the first line reports 0 students.- A static method has no
this, so it cannot readnameoriddirectly. It can use other static members such ascountandSCHOOL. b.countworks but is misleading, because it looks like an object’s own value. WriteStudent.countinstead.- Java’s own utility methods, like
Math.maxandInteger.parseInt, are static for the same reason: they need no object.
Static Blocks and the final Keyword
import java.util.ArrayList;
import java.util.List;
public class Main {
static final double VAT_RATE;
static { // runs once, when the class loads
VAT_RATE = 0.15;
System.out.println("static block ran");
}
static final class MathUtil { // final class: cannot be extended
private MathUtil() {} // no objects of a utility class
static int square(int x) { return x * x; }
}
public static void main(String[] args) {
System.out.println("main started, VAT = " + VAT_RATE);
System.out.println(MathUtil.square(9));
final int limit = 3;
// limit = 4; // compile error: cannot assign a value to final variable
final List<String> names = new ArrayList<>();
names.add("Rina"); // allowed: the list itself can change
names.add("Joya");
// names = new ArrayList<>(); // compile error: the reference is final
System.out.println(names + " limit=" + limit);
}
}
Output
static block ran
main started, VAT = 0.15
81
[Rina, Joya] limit=3
- A
static { … }block runs once, when the class is first loaded, beforemain. It is useful for setting up static data that needs more than one line. static final double VAT_RATEis a constant: one shared value that can never change. By convention constants use UPPER_SNAKE_CASE.- A
finallocal variable such aslimitcan be assigned only once. The commented-out line would not compile. final List<String> namesfixes the reference, not the object. You can still add to the list, but you cannot pointnamesat a different list. For a truly unchangeable list, useList.of(...).- A
final classcannot be extended, and a private constructor stops anyone creating objects. Together they make a clean utility class.Stringis a final class.
static and final at a Glance
| Applied to | static | final |
|---|---|---|
| Field | One copy shared by the class | Assigned once, then read-only |
| Method | Called on the class; no this | Cannot be overridden by subclasses |
| Class | Only for nested classes (no outer object needed) | Cannot be extended |
| Local variable | Not allowed | Assigned once |
| Block | Runs once when the class loads | Not applicable |
Common Mistakes
- Calling an instance method from
mainwithout an object, which gives “non-static method cannot be referenced from a static context”. Create an object first, or make the method static. - Using static fields for per-object data, so every object accidentally shares one value.
- Thinking
finalmakes an object immutable. It only stops reassignment of the variable. - Too much static state, which acts like global variables and makes code hard to test.
Practice Exercises
Exercise 1. Add a static method resetCount() to Student that sets the counter back to 0. Why can it not also clear every student’s name?
Show answer
static void resetCount() {
count = 0;
}
A static method is not attached to any object, so there is no single name for it to change. It would need a reference to each Student object.
Exercise 2. Does this compile? final int[] scores = {1, 2, 3}; scores[0] = 10;
Show answer
Yes. final stops scores from pointing to another array, but the elements of the array can still change. scores = new int[3]; would not compile.
Frequently Asked Questions
Why is main declared static?
The JVM must call main before any object of your class exists. Making it static lets the JVM call it on the class directly.
What is the difference between final, finally and finalize?
final is a keyword for variables, methods and classes. finally is the block after try/catch that always runs. finalize() was an old cleanup method called by the garbage collector; it is deprecated and should not be used.
Summary
staticmembers belong to the class and are shared.- Static methods have no
thisand cannot use instance fields directly. finalmeans assign once, never override, or never extend.static finalcreates constants; a final reference can still point to a changeable object.
