These are the notes for Java episode 16. In episode 15 our Student objects got constructors, and two problems were left: every student object carried its own copy of the school's name, and a counter of students created didn't work. One keyword fixes both: static. You will see what a static field is and where it lives in memory, write static methods, find out why main is static, meet the famous error "non-static variable cannot be referenced from a static context", run static blocks and see their exact order, and make static final constants. Every example below runs as-is in the SyntaxPilot compiler, with its real output from javac 21.
The problem: the school gets a new name
A school has 1,000 students, and every ID card prints the school's name: DPS Noida. Then the school is renamed DPS Greater Noida. Now 1,000 cards must be reprinted one by one, and if even one is missed, the school has two names and nobody knows which is right.
Our Student class has exactly this problem. Here school is an ordinary field, so every object gets its own copy:
class Student {
String name;
String school = "DPS Noida";
Student(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Student a = new Student("Aarav");
Student b = new Student("Diya");
a.school = "DPS Greater Noida";
System.out.println(a.name + ": " + a.school);
System.out.println(b.name + ": " + b.school);
}
}
Aarav: DPS Greater Noida
Diya: DPS Noida
Two students of the same school, and the program now believes they go to different schools.
Why it went wrong
- A normal field is an instance field: every object (every instance) gets its own copy.
- Changing Aarav's copy doesn't touch Diya's copy.
- 1,000 objects hold 1,000 identical copies of the same text: wasted memory, and 1,000 places to update.
- The real mistake: a student's name is different for every student, but the school's name is the same for all of them. It belongs to the school (the class), not to each student (each object).
static variables: one notice board instead of 1,000 photocopies
| In a school | In Java |
|---|---|
| A photocopy of a notice in every student's bag | instance field: one copy per object |
| One notice pinned on the corridor notice board | static field: one copy for the whole class |
| Change the notice once, everyone sees it | Student.school = "...": every object sees the new value |
A static field (also called a static variable or class variable) is declared with the word static before the type. There is exactly one copy, and it belongs to the class itself, not to any object. You use it through the class name: Student.school.
class Student {
String name;
static String school = "DPS Noida";
Student(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Student a = new Student("Aarav");
Student b = new Student("Diya");
Student.school = "DPS Greater Noida";
System.out.println(a.name + ": " + a.school);
System.out.println(b.name + ": " + b.school);
}
}
Aarav: DPS Greater Noida
Diya: DPS Greater Noida
One change, every student agrees.
Java also lets you read a static field through an object (
a.school, line 14), and it compiles without complaint. But it's misleading: it looks like Aarav's own copy. Always writeClassName.field(Student.school) so the reader knows it is shared.
Where a static field lives
STACK (main) HEAP (objects made with new) CLASS (one copy)
a ──────────────► Student { name = "Aarav" } Student.class
b ──────────────► Student { name = "Diya" } school = "DPS Greater Noida"
- Local variables
aandb(references) live on the stack (episode 14). - The objects live on the heap; each holds only what is really its own:
name. - The static field lives with the class. The JVM sets it up once, when the class is loaded. (Inside the JVM this storage is part of the class's data; you don't need the exact JVM area name to use
staticcorrectly. Episode 43 covers JVM memory areas.)
Counting students: an instance counter fails
The principal asks: how many students joined this year? Our first idea: a count field that the constructor increases.
class Student {
String name;
int count = 0;
Student(String name) {
this.name = name;
count++;
}
}
public class Main {
public static void main(String[] args) {
Student a = new Student("Aarav");
Student b = new Student("Diya");
Student c = new Student("Kabir");
System.out.println(a.count + " " + b.count
+ " " + c.count);
}
}
1 1 1
Expected 3, got 1 1 1. count is an instance field: every new object starts with its own fresh count = 0, and count++ adds one to that object's copy only. Three objects, three separate counters, each stuck at 1. It's like giving every student a notebook and asking each to count himself.
The fix: a static counter and a static method
A real school keeps one tally at the office. Make count static, and add a static method to read it:
class Student {
String name;
static int count = 0;
Student(String name) {
this.name = name;
count++;
}
static int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Before: " + Student.getCount());
new Student("Aarav");
new Student("Diya");
new Student("Kabir");
System.out.println("After: " + Student.getCount());
System.out.println(Math.max(274, 255));
}
}
Before: 0
After: 3
274
- Every constructor call adds one to the same shared counter.
Student.getCount()worked before any student existed ("Before: 0"). A static member belongs to the class, so it exists before, and without, any object.- You've used static methods since episode 1:
Math.max(274, 255),Arrays.sort(...),Arrays.toString(...). You never wrotenew Math(); you just asked the class.
static methods: ask the office, or ask a student?
| In a school | In Java |
|---|---|
| Ask the office: "How many students joined?" | Student.getCount(): a static method, called on the class, no object needed |
| Ask Diya: "What's your name?" | diya.name: needs that particular object (instance member) |
| The calculator on the office desk, anyone can use it | Math.max(a, b): a static helper method |
A static method is a method declared with static. It is called on the class (ClassName.method()), and it does not run on any particular object. An instance method (no static) always runs on one object: aarav.print().
Why is main static?
public static void main(String[] args)
When you run a program the JVM starts and no objects exist yet. An instance method can only be called on an object, so the JVM couldn't call an instance main. It calls Main.main(args) on the class, exactly like Student.getCount(), and then your code creates the objects. That is the whole reason main is static.
The static context errors
A static context is any code that runs without a current object: a static method, a static block, or a static field's initializer. Code there cannot use instance fields, instance methods or this directly. Ask yourself: whose name? There might be zero students or a thousand.
class Student {
String name;
static int count = 0;
static void show() {
System.out.println(name);
}
}
public class Main {
public static void main(String[] args) {
Student.show();
}
}
Main.java:5: error: non-static variable name cannot be referenced from a static context
System.out.println(name);
^
1 error
The same trap inside Main:
public class Main {
void greet() {
System.out.println("Namaste!");
}
public static void main(String[] args) {
greet();
}
}
Main.java:7: error: non-static method greet() cannot be referenced from a static context
greet();
^
1 error
Two fixes: make greet static, or create an object and call it on that object:
public class Main {
void greet() {
System.out.println("Namaste!");
}
public static void main(String[] args) {
Main m = new Main();
m.greet();
}
}
Namaste!
And this (the current object) doesn't exist in static code either:
class Student {
String name;
static void show() {
System.out.println(this.name);
}
}
Main.java:4: error: non-static variable this cannot be referenced from a static context
System.out.println(this.name);
^
1 error
Who can use what
| Code in... | static fields / methods | instance fields / methods | this |
|---|---|---|---|
| a static method | yes | no (whose?) | no |
| an instance method or constructor | yes | yes (its own object's) | yes |
The one question: does this belong to everyone, or is it different for each object? Same for everyone → static. Different per object → not static.
static blocks: the morning set-up, done once
Before any class starts, the school staff pins the timetable and the grade table on the board, once. Students arrive and just read it; nobody re-pins it for each student. Java's place for one-time set-up of static data is a static block (also called a static initializer): the word static followed by { ... } inside a class.
class Student {
static String[] grades;
static {
System.out.println("Student: loading grade table");
grades = new String[] {"A", "B", "C", "D", "F"};
}
String name;
Student(String name) {
this.name = name;
System.out.println("New student: " + name);
}
}
public class Main {
static {
System.out.println("Main: static block");
}
public static void main(String[] args) {
System.out.println("main starts");
new Student("Aarav");
new Student("Diya");
System.out.println(Student.grades.length + " grades");
}
}
Main: static block
main starts
Student: loading grade table
New student: Aarav
New student: Diya
5 grades
The order, explained:
- The JVM must load the
Mainclass before it can callmain, and loading a class runs its static blocks. SoMain: static blockprints beforemain starts. Studentis loaded only when it is first used (creating Aarav). Its static block runs then.- It runs exactly once: creating Diya did not run it again.
- Static blocks run top to bottom, together with static field initializers, in the order they are written.
static final: a shared constant
The pass mark is the same for every student (static) and must never change (final, episode 2). Together, static final makes a constant: one copy, locked. Constants are written in CAPITAL_LETTERS with underscores.
class Student {
static final int PASS_MARK = 33;
}
public class Main {
public static void main(String[] args) {
System.out.println(Student.PASS_MARK);
Student.PASS_MARK = 40;
}
}
Main.java:8: error: cannot assign a value to static final variable PASS_MARK
Student.PASS_MARK = 40;
^
1 error
Math.PI is exactly this: a static final constant in the Math class.
What you just invented
| Problem | Invention |
|---|---|
| A copy of the school in every object went out of sync | static field: one copy per class |
| "How many students?" needs no particular student | static method, called on the class |
| The program must start when no objects exist | main is static |
| One-time set-up of shared data | static block |
| A shared value that must never change | static final constant |
The next problem: any code anywhere can write aarav.total = -50; or set a mark to 500. It compiles, it runs, and nothing stops it. Next episode: encapsulation.
Common mistakes (and the real error messages)
| Mistake | Real message | Why | Fix |
|---|---|---|---|
static void show() { System.out.println(name); } |
error: non-static variable name cannot be referenced from a static context |
A static method has no object: whose name? | Make it an instance method, or pass the object in as a parameter |
greet(); called directly from main |
error: non-static method greet() cannot be referenced from a static context |
greet needs an object |
new Main().greet(), or make greet static |
this.name inside a static method |
error: non-static variable this cannot be referenced from a static context |
No current object in static code | Remove this, or drop static |
Student.PASS_MARK = 40; |
error: cannot assign a value to static final variable PASS_MARK |
final means it can't change |
Change the declaration itself |
int count without static for a shared counter |
no error, prints 1 1 1 |
Each object counts only itself | static int count |
a.school = "..." to change a static field |
no error, but misleading | Looks like one object's own copy | Write Student.school = "..." |
Mini project: the school admission desk
One Student class that uses everything from today: a static school name, a static counter that hands out roll numbers, a constant pass mark, a grade table loaded in a static block, static helper methods and an instance method that prints a report line.
class Student {
static String school = "DPS Noida";
static final int PASS_MARK = 33;
static int count = 0;
static int[] cutoffs;
static char[] letters;
static {
cutoffs = new int[] {90, 75, 60, 40};
letters = new char[] {'A', 'B', 'C', 'D'};
System.out.println("Grade table loaded");
}
String name;
int roll;
int percent;
Student(String name, int percent) {
count++;
this.roll = count;
this.name = name;
this.percent = percent;
}
static char gradeFor(int p) {
for (int i = 0; i < cutoffs.length; i++) {
if (p >= cutoffs[i]) return letters[i];
}
return 'F';
}
static boolean isPass(int p) {
return p >= PASS_MARK;
}
void print() {
System.out.println(roll + ". " + name + " " + percent + "% "
+ gradeFor(percent) + (isPass(percent) ? " PASS" : " FAIL")
+ " (" + school + ")");
}
}
public class Main {
public static void main(String[] args) {
Student[] cls = {
new Student("Aarav", 85),
new Student("Diya", 91),
new Student("Kabir", 28)
};
Student.school = "DPS Greater Noida";
for (Student s : cls) s.print();
System.out.println("Students: " + Student.count);
}
}
Grade table loaded
1. Aarav 85% B PASS (DPS Greater Noida)
2. Diya 91% A PASS (DPS Greater Noida)
3. Kabir 28% F FAIL (DPS Greater Noida)
Students: 3
Notice that the school was renamed after the students were created, and every report line shows the new name: there's only one copy.
Practice
- Give each
Studentan automatic roll number (1, 2, 3...) using a static counter. - Add
static int highestthat always holds the best total created so far. - Write
static boolean isPass(int marks)that usesPASS_MARK = 33. - Predict the output, then run it:
class School {
static {
System.out.println("A");
}
static String name = "DPS";
}
public class Main {
static {
System.out.println("B");
}
public static void main(String[] args) {
System.out.println("C");
System.out.println(School.name);
System.out.println(School.name);
}
}
Solutions
1-3 together (tested):
class Student {
static final int PASS_MARK = 33;
static int count = 0;
static int highest = 0;
String name;
int roll;
int total;
Student(String name, int total) {
count++;
roll = count;
this.name = name;
this.total = total;
if (total > highest) highest = total;
}
static boolean isPass(int marks) {
return marks >= PASS_MARK;
}
}
public class Main {
public static void main(String[] args) {
Student a = new Student("Aarav", 255);
Student b = new Student("Diya", 274);
Student c = new Student("Kabir", 135);
System.out.println(a.roll + " " + b.roll + " " + c.roll);
System.out.println("Highest: " + Student.highest);
System.out.println(Student.isPass(28) + " " + Student.isPass(33));
}
}
1 2 3
Highest: 274
false true
roll = count; copies the shared counter into the object's own field at the moment it is created, so each student keeps their number even after count grows.
4: Main is loaded first, so its static block prints B. Then main prints C. The first use of School.name loads School, which prints A, then DPS. The second use doesn't load it again:
B
C
A
DPS
DPS
Quick quiz
class Ticket {
static int sold = 0;
int seat;
Ticket() {
sold++;
seat = sold;
}
}
// in main:
Ticket a = new Ticket();
Ticket b = new Ticket();
Ticket c = new Ticket();
System.out.println(a.seat + " " + c.seat + " " + a.sold);
A. 1 1 1 B. 1 3 3 C. 3 3 3 D. 1 2 3
Answer
B. 1 3 3. sold is static: one counter, 3 after three tickets. seat is an instance field: each ticket keeps the value sold had when it was made, so a.seat is 1 and c.seat is 3. a.sold reads the one shared counter: 3.
Interview questions
- What is the difference between a static and an instance variable? A static variable has one copy per class, shared by all objects, and exists even before any object is created; an instance variable has one copy per object.
- Why is
mainstatic? The JVM must call it before any object exists; a static method can be called on the class without an object. - Can a static method access instance variables? Not directly, because there is no current object. It can if it is given an object, e.g.
static void show(Student s) { System.out.println(s.name); }. - Can we use
thisorsuperin a static method? No: both refer to the current object, and static code has none. - When does a static block run? Once, when the class is loaded (initialized), which happens on its first active use: creating an object, calling a static method, or using a static field that isn't a compile-time constant. For the main class, that is before
mainruns. - Can an instance method use static members? Yes, an instance method can use both instance and static members.
- What is
static final? A constant: one shared copy that cannot be reassigned, likeMath.PI. - Can you call a static method through an object reference? It compiles (
a.getCount()), but it is bad style; the call depends only on the class, so writeStudent.getCount().
Glossary
| Term | Meaning | Example |
|---|---|---|
| instance | one object made from a class | new Student("Aarav") |
| instance field (instance variable) | a field with one copy inside every object | String name; |
static |
a keyword meaning "belongs to the class, not to any one object" | static int count; |
| static field (class variable) | a field with exactly one copy, shared by all objects of the class | static String school |
| static method (class method) | a method called on the class, with no current object | Student.getCount(), Math.max(a, b) |
| instance method | a method that runs on one particular object | aarav.print() |
| static context | code with no current object: a static method, static block or static field initializer | inside main |
this |
a reference to the current object | this.name = name; |
| class loading | the JVM reading a class into memory and setting up its static data, once | first use of Student |
| static block (static initializer) | static { ... } code that runs once when the class is loaded |
filling a grade table |
| constant | a value that never changes | PASS_MARK |
static final |
one shared copy that cannot be reassigned | static final int PASS_MARK = 33; |
Math.PI |
a static final constant in Java's Math class |
3.141592653589793 |
Summary
- An instance field has one copy per object; a static field has one copy for the whole class. Use it as
ClassName.field. - A static counter (
static int count,count++in the constructor) counts every object created. - Static methods are called on the class and need no object:
Student.getCount(),Math.max,Arrays.sort. mainis static because the JVM calls it before any object exists.- Static code cannot use instance fields, instance methods or
this: "non-static ... cannot be referenced from a static context". - A static block runs once, when the class is loaded:
Main's beforemain, other classes on first use. static finalmakes a shared constant; reassigning it is a compile error.
Next episode: Encapsulation, access modifiers and packages. Right now any code can write aarav.total = -50; and Java says nothing. Next we lock the data inside the object with private, open controlled doors with methods, and organise classes into packages.