static and final in Java
Use static for data and methods that belong to the whole class, and final for values, methods and classes that must not change.
Learning objectives
- βTell instance members apart from static (class-level) members
- βUse static variables for shared data and static methods for helpers
- βUse final for constants, fixed fields and references that must not be reassigned
- βKnow what final means on a method and on a class
π‘ Key points
- A static member belongs to the class, not to any one object. There is exactly one copy, shared by all objects.
- Use the class name to reach static members: Student.count, Math.max(a, b). No object is needed.
- A static method cannot use instance variables or this directly, because there is no current object inside it.
- A static block runs once, when the class is first loaded, before main or any other code uses the class.
- A final variable can be assigned only once. A blank final field (declared without a value) must be set in every constructor, or in a static block if the field is static.
- final on a reference stops reassignment, not changes. The elements of a final array can still be modified.
- A final method cannot be overridden, and a final class (like String) cannot be extended.
π» Code examples(5)
class Student {
static int count = 0; // one copy for the class
int rollNo; // one copy per object
String name;
Student(String name) {
this.name = name;
count++;
rollNo = count;
}
}
public class CountDemo {
public static void main(String[] args) {
Student a = new Student("Amit");
Student p = new Student("Priya");
Student r = new Student("Ravi");
System.out.println(a.name + " " + a.rollNo);
System.out.println(p.name + " " + p.rollNo);
System.out.println(r.name + " " + r.rollNo);
System.out.println("Total: " + Student.count);
}
}
Amit 1 Priya 2 Ravi 3 Total: 3
class MarksUtil {
static double percent(int got, int total) {
return got * 100.0 / total;
}
static boolean isDistinction(double pc) {
return pc >= 75;
}
}
public class UtilDemo {
public static void main(String[] args) {
double pc = MarksUtil.percent(436, 500);
System.out.println(pc);
System.out.println(MarksUtil.isDistinction(pc));
System.out.println(Math.max(45, 72));
System.out.println(Math.sqrt(144));
}
}
87.2 true 72 12.0
public class Counter {
int clicks = 0; // instance variable
static int total = 0; // static variable
void click() {
clicks++; // instance method: can use both
total++;
}
static void report() {
// clicks++; // error: non-static variable
System.out.println("Total clicks: " + total);
}
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
c1.click();
c1.click();
c2.click();
System.out.println("c1: " + c1.clicks);
System.out.println("c2: " + c2.clicks);
report();
}
}
c1: 2 c2: 1 Total clicks: 3
public class Config {
static final double GST_RATE;
static String appName;
static {
System.out.println("Static block runs first");
GST_RATE = 0.18;
appName = "ShopBill";
}
public static void main(String[] args) {
System.out.println("main starts");
double price = 1000;
double gst = price * GST_RATE;
System.out.println(appName + ": GST = Rs." + gst);
}
}
Static block runs first main starts ShopBill: GST = Rs.180.0
class Exam {
final String subject; // blank final
static final int MAX_MARKS = 100; // constant
Exam(String subject) {
this.subject = subject; // set once
}
}
public class FinalDemo {
public static void main(String[] args) {
Exam e = new Exam("Physics");
// e.subject = "Maths"; // error: final
final int[] marks = {70, 80, 90};
marks[0] = 75; // allowed
// marks = new int[3]; // error: final
System.out.println(e.subject + " out of "
+ Exam.MAX_MARKS);
System.out.println(marks[0]);
}
}
Physics out of 100 75
π― Practice
Q1. A class has static int count, and there are three objects. One object runs count++. What do the other two see?+
The new value. There is only one count, shared by every object of the class.
Q2. Why can't a static method use this?+
this means the current object, but a static method is called on the class, not on an object. There is no current object for this to refer to.
Q3. Will this compile? final int x; x = 10; x = 20;+
No. The first assignment is allowed (a final local may be assigned once, after it is declared). The second gives 'variable x might already have been assigned'.
Q4. Write a class Circle with a constant PI = 3.14 shared by all objects and a static method area(double r).+
class Circle { static final double PI = 3.14; static double area(double r) { return PI * r * r; } } // Circle.area(7) gives 153.86
Q5. final int[] a = {1, 2}; Which line fails: a[0] = 5; or a = new int[2];?+
a = new int[2]; fails with 'cannot assign a value to final variable a'. final stops the reference being reassigned, but the array itself can still change, so a[0] = 5 is fine.
π Notes
static vs instance in one picture
Think of a classroom:
- Instance variable: each student's own
nameandrollNo. Every object has its own copy. - static variable: the class teacher's name, or the total number of students. There is one value for the whole class.
- Instance method:
printReport()needs a particular student, so call it ass.printReport(). - static method:
MarksUtil.percent(436, 500)needs no particular student, so call it on the class.
Constants are usually both: static final means one copy, never changed. By convention they are written in SCREAMING_SNAKE_CASE.
final on methods and classes
You will meet extends tomorrow. For now, just know that final can block it:
final class TaxRules { }
// class MyRules extends TaxRules { }
// error: cannot inherit from final TaxRules
String is a final class, so nobody can extend it and change how strings behave. A final method can be inherited but not overridden.
Common mistakes
- Calling an instance method straight from
main. This gives non-static method show() cannot be referenced from a static context. Create an object first (new Counter().show()), or make the method static if it really uses no instance data. - Making everything static to silence that error. A
static String namewould give every student the same name. - Reaching static members through an object.
s.countcompiles but hides the fact thatcountis shared. WriteStudent.count. - Thinking
finalfreezes an object. It only stops the variable from pointing somewhere else. The object's contents can still change.
Next: Day 14, Inheritance. You will build new classes on top of existing ones with extends and super.