A shared counter gives every object an id
static means "belongs to the class itself, not to any one object". A static field has exactly one copy shared by everyone, a static method runs without an object, and a static block runs once when the class is first initialised.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a utility class Stats (private constructor) with static methods max(int[] a) and average(int[] a). Use them on {4, 8, 15, 16, 23, 42}.
Write a class User that gives each new user an id from a static counter and has a static method count(). Create three users and print their ids and the count.
Write a class Colors whose static block fills a static String[] NAMES = new String[3] with "red", "green", "blue" and prints Colors ready. In main, print a line, then Colors.NAMES[1], then Colors.NAMES[2].
Explain it without notes
What is the difference between a static field and an instance field? Give an example where each is the right choice.
Why can't a static method use this or instance fields directly?
When does the JVM initialise a class, and what runs during initialisation?
What are the advantages of a static factory method over a constructor?
Why is mutable static state considered risky?
Expected output
issued before: 0
Ticket #1 Asha (of 3)
Ticket #2 Ben (of 3)
Ticket #3 Chen (of 3)
issued after: 3
F of 100 C = 212.0