Skip to lesson

A static variable (static field) is one value shared by every object of a class. Because every constructor and every method sees that same value, it can count objects, hand out the next ID, or hold a setting for the whole class.

Counting objects

A static variable (also called a class variable) is a field declared with static. Only one copy exists for the whole class: it is created when the class is loaded and is shared by every object of that class.

A school app must show how many students have joined. Put count++; in the constructor, where count is a static field: every new runs the constructor once, so the one shared count goes up by 1 per object.

Example 1 · A static counter

CounterDemo.javaJava
class Student {    static int count = 0;    String name;
    Student(String name) {        this.name = name;        count++;    }}
public class CounterDemo {    public static void main(String[] args) {        new Student("Aarav");        System.out.println("Students: " + Student.count);        new Student("Priya");        new Student("Kavya");        System.out.println("Students: " + Student.count);    }}
Output
Students: 1
Students: 3

What this code does

  • Every new Student(...) runs the constructor, and count++ adds 1 to the one shared count.
  • Read the counter with the class name: Student.count.

Example 2 · Mistake: a counter without static

CounterBugDemo.javaJava
class Student {    int count = 0;    String name;
    Student(String name) {        this.name = name;        count++;    }}
public class CounterBugDemo {    public static void main(String[] args) {        Student a = new Student("Aarav");        Student b = new Student("Priya");        Student c = new Student("Kavya");        System.out.println(a.count + " " + b.count + " " + c.count);    }}
Output
1 1 1

What this code does

  • Without static, each object has its own count, which starts at 0 and goes up once.
  • So every object says 1. Adding static back gives one shared counter that reaches 3.

Without static, every object gets its own count, which starts at 0 and stops at 1, so every object reports 1 (Example 2). That is the most common static bug.

A static int starts at 0 if you give it no value, just like an instance int field.

Generating IDs

Roll numbers must go 101, 102, 103 with no repeats. Use two fields: a static nextRoll, the class's "which number comes next?", and an instance rollNo, each student's own number.

Example 3 · Roll numbers from a static counter

RollDemo.javaJava
class Student {    private static int nextRoll = 101;    private int rollNo;    private String name;
    Student(String name) {        this.name = name;        rollNo = nextRoll;        nextRoll++;    }
    void show() {        System.out.println(rollNo + " " + name);    }}
public class RollDemo {    public static void main(String[] args) {        new Student("Aarav").show();        new Student("Priya").show();        new Student("Kavya").show();    }}
Output
101 Aarav
102 Priya
103 Kavya

What this code does

  • nextRoll is shared and moves on after each object; rollNo is each student's own copy.
  • Both fields are private: no other class can change the counter and break the numbering.

The order inside the constructor matters: copy the counter into the object first, then move the counter on. Step through it and watch which value is shared and which belongs to one object.

Trace the code

Watch the shared counter hand out roll numbers

class Student {
static int nextRoll = 101;
int rollNo;
String name;
Student(String name) {
this.name = name;
rollNo = nextRoll;
nextRoll++;
}
}
public class RollTrace {
public static void main(String[] args) {
Student a = new Student("Aarav");
Student b = new Student("Priya");
System.out.println(a.rollNo + " " + b.rollNo + " " + Student.nextRoll);
}
}

Variables

nextRoll
101

Output

(nothing printed yet)

Line 2new Student on line 15 is the first use of Student, so Java loads the class and sets the one shared nextRoll to 101.

Step 1 of 9

Shared settings, kept private

A library charges the same late fee per day for every book. Keep such a setting in a private static field with a static getter and setter, called with the class name: Library.setFinePerDay(5).

Example 4 · A shared setting with a static setter

FineDemo.javaJava
class Library {    private static int finePerDay = 2;
    static int getFinePerDay() {        return finePerDay;    }
    static void setFinePerDay(int fine) {        if (fine < 0) {            System.out.println("Fine cannot be negative");            return;        }        finePerDay = fine;    }
    int fine(int daysLate) {        return daysLate * finePerDay;    }}
public class FineDemo {    public static void main(String[] args) {        Library branch = new Library();        System.out.println("4 days late: Rs. " + branch.fine(4));        Library.setFinePerDay(5);        Library.setFinePerDay(-1);        System.out.println("4 days late: Rs. " + branch.fine(4));        System.out.println("Fine per day: Rs. " + Library.getFinePerDay());    }}
Output
4 days late: Rs. 8
Fine cannot be negative
4 days late: Rs. 20
Fine per day: Rs. 5

What this code does

  • The fine rate is one value for the whole library, so it is a private static field.
  • The static setter is called with the class name and refuses a negative value, just like an instance setter would.

The setter checks the value, so no one can set a negative fee, just like the setters in Getters and setters (opens in a new tab). Static methods are covered in full in the next lesson (opens in a new tab).

Why changing it through an object is confusing

Only Rohan is a student, so only his ticket should be half price. But t1.giveStudentDiscount() writes fare = fare / 2;, and fare is static: the one shared fare is halved for every ticket.

Example 5 · Mistake: an instance method that changes a static field

DiscountBugDemo.javaJava
class Ticket {    static int fare = 100;    String passenger;
    Ticket(String passenger) {        this.passenger = passenger;    }
    void giveStudentDiscount() {        fare = fare / 2;    }}
public class DiscountBugDemo {    public static void main(String[] args) {        Ticket t1 = new Ticket("Rohan");        Ticket t2 = new Ticket("Diya");        t1.giveStudentDiscount();        System.out.println(t1.passenger + ": Rs. " + t1.fare);        System.out.println(t2.passenger + ": Rs. " + t2.fare);    }}
Output
Rohan: Rs. 50
Diya: Rs. 50

What this code does

  • Only Rohan is a student, but fare is static, so halving it changes the fare for every ticket.
  • Fix: keep the base fare static and add an instance field such as int discount; that only Rohan's ticket sets.

Before you change a static field, ask: do I mean to change it for every object? If yes, write Ticket.fare = ...; so the reader sees it. If not, the value must be an instance field.

Predict the output

Predict the shared and own values

Read the code and pick what it prints.

Round 1 of 3

After three orders this should print 3. What does it print?

class Order {
int count = 0;
Order() {
count++;
}
}
public class OrderCount {
public static void main(String[] args) {
Order a = new Order(), b = new Order(), c = new Order();
System.out.println(c.count);
}
}

Next step

Check your understanding

12 quick questions