static fields and methods

A member declared static belongs to the class, not to an object: one field for the whole class, one method that runs without a receiver. The modifier is the difference between state that every object shares and state that each object has for itself.

static

A static field is created once, when the class is loaded, and every object sees the same value. A static method is called on the class name, has no this, and cannot read an instance field. The compiler enforces the last rule, which is why lesson 017 showed it as an error.

A field shared by objects

The class below numbers its objects: every constructor increments one shared counter and stores the new value in its own final field. The counter is static, the id is not, and the output shows both.

The file Counter.java:

public class Counter { static final int MAX = 3; private static int created; private final int id; Counter() { created++; this.id = created; } int getId() { return id; } static int created() { return created; } public static void main(String[] args) { Counter a = new Counter(); Counter b = new Counter(); Counter c = new Counter(); System.out.println("created: " + Counter.created()); System.out.println("ids: " + a.getId() + " " + b.getId() + " " + c.getId()); System.out.println("max: " + Counter.MAX); } }

javac -Xlint:all Counter.java
java Counter

created: 3
ids: 1 2 3
max: 3

created is one variable and reaches 3, while each object has its own id with the value it saw. The static field starts at 0 because it is an int, and the first constructor increments it to 1 before the first id is read.

A static method

created() is static because it answers a question about the class rather than about one object. It is called as Counter.created(), and Java also allows a.created(), which looks like an instance call and is a bad habit: the compiler uses the static method and ignores the object.

A static method can call other static methods and read static fields. It cannot call an instance method or read an instance field without an object, because there is no object to work on. That is the rule the error of lesson 017 broke.

The static block

A static { ... } block runs once, when the class is initialised, before the first object is created and before main runs. It is for initialisation that a field initialiser cannot express, such as a loop or a value read from a property.

public class StaticBlock { static int value; static { value = 42; System.out.println("static block"); } int instance = init(); static int init() { System.out.println("instance init"); return 1; } public static void main(String[] args) { System.out.println("main: " + value); StaticBlock a = new StaticBlock(); StaticBlock b = new StaticBlock(); System.out.println(a.instance + " " + b.instance); } }

javac -Xlint:all StaticBlock.java
java StaticBlock

static block
main: 42
instance init
instance init
1 1

The static block runs once, before main, and the instance initialiser runs once per object. The order of the two lines is the order of class initialisation against object creation, and a program that prints from both is a quick way to see it.

static final constants

static final int MAX = 3 is a constant of the class: one value, assignable once, and the compiler may copy it into the code that reads it. The convention writes its name in capitals, and the JDK does the same for Integer.MAX_VALUE and Math.PI.

A static final field of a mutable type is a constant reference, not a constant value: a static final list can still be added to. The immutable classes of lesson 042 and the unmodifiable views of the collections part are the fix.

Exercises

  1. Reset created in Counter.java before the second object and predict the ids.
  2. Add a static method max() that returns MAX and call it from main.
  3. Move the assignment of value in StaticBlock.java from the static block into the field declaration and compare the output.
  4. Try to read id from a static method of Counter.java. What does javac say?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How many copies of a static field exist?

    Answer

    One for the class

    A static field belongs to the class, so every object reads and writes the same one.

  2. What can a static method not do?

    Answer

    Read an instance field without an object

    A static method has no this, so instance state needs an object passed to it.

  3. When does a static block run?

    Answer

    Once, when the class is initialised

    Class initialisation happens once, before the first use of the class.

  4. What does this program print? public class Q1 { static int count; public static void main(String[] args) { count++; count++; System.out.println(count); } }

    Answer

    2

    The static field starts at 0 and is incremented twice.

  5. What does this program print? public class Q2 { static int count; int value; public static void main(String[] args) { Q2 a = new Q2(); Q2 b = new Q2(); a.value = 5; b.value = 7; a.count = 3; System.out.println(a.value + " " + b.value + " " + b.count); } }

    Answer

    5 7 3

    The instance fields differ, and the static count is one value seen through both names.

  6. What does this program print? public class Q3 { static int value = init(); static int init() { return 4; } public static void main(String[] args) { System.out.println(value); } }

    Answer

    4

    A static field initialiser may call a static method, and 4 is stored before main runs.

  7. What does this program print? public class Q4 { static final int MAX = 3; public static void main(String[] args) { System.out.println(MAX * 2); } }

    Answer

    6

    The constant holds 3, and the multiplication gives 6.

  8. What is the first line of the compiler output for this program? public class Q5 { int value = 1; static int get() { return value; } public static void main(String[] args) { System.out.println(get()); } }

    Answer

    error: non-static variable value cannot be referenced from a static context

    The static method has no object, so the instance field is not in scope.

  9. What does this program print? public class Q6 { static int total; public static void main(String[] args) { add(2); add(3); System.out.println(total); } static void add(int n) { total += n; } }

    Answer

    5

    The static method writes the static field, and the two calls add 2 and 3.

  10. Can a static final field of a list type be changed?

    Answer

    The reference cannot, but the list contents can

    final stops a new assignment to the field, not calls on the object it points at.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev