Unit 5 · Applying Java OOP · 9 min
static and final
`static` belongs to the class rather than to any one object. `final` means something cannot be changed after it is set.
Why this matters
Counters, constants and utility methods all depend on these two keywords, and they appear in nearly every exam paper.
Example
Java
class Student {
static String college = "ABC Degree College"; // shared by all students
static int count = 0; // shared counter
final int rollNumber; // set once, never changed
String name;
Student(String name, int rollNumber) {
this.name = name;
this.rollNumber = rollNumber;
count++;
}
static void showCount() { // no object needed
System.out.println("Total students: " + count);
}
}
public class Main {
public static void main(String[] args) {
new Student("Ananya Rao", 12);
new Student("Arjun", 15);
System.out.println(Student.college);
Student.showCount();
}
}Output
ABC Degree College Total students: 2
Step by step
- 1`static String college` exists once in memory, shared by every Student object.
- 2`count++` inside the constructor increases the shared counter each time an object is created.
- 3`final int rollNumber` must be assigned exactly once — here in the constructor.
- 4`Student.showCount()` is called on the class name, without any object.
- 5A static method cannot use non-static fields directly, because there is no 'current object'.
Key points
- static members belong to the class, shared by all objects
- static methods cannot use this or instance fields
- final variable = constant, final method = cannot be overridden, final class = cannot be extended
- static final is the usual way to declare constants
Common mistakes
- Using an instance field inside a static method
- Trying to reassign a final variable
- Expecting each object to have its own copy of a static field
Try it yourself
- Add a static counter to your BankAccount class to count accounts created.
- Declare a static final double PI and use it in an area calculation.