JAVA-102 · Lesson 4 of 12 · 22 min
Static members and utility classes
▶ Video coming soon A video version of this lesson is on the way.
Every booking in Hamza's system needs a number the shop can write on a repair tag, and every number must be different. A booking cannot choose its own number, because it does not know about the others. The number counter belongs to the Booking class as a whole, not to any one booking. The plan for Wednesday, February 3, 2027 is to look at that idea, the static member, which JAVA-101 used from its first program without explaining fully, and at the small classes of static helpers that every Java program uses.
Instance members and static members
An instance field belongs to each object: every booking has its own customer and its own status. A static field, declared with the word static, belongs to the class itself, and there is exactly one copy of it no matter how many objects exist, even none. In the same way, an instance method runs on a particular object and can use its fields, while a static method belongs to the class, is called through the class name and has no current object.
public class Main {
public static void main(String[] args) {
System.out.println("Bookings made so far: " + Booking.made());
Booking a = new Booking("Ana Ruiz");
Booking b = new Booking("Theo Park");
Booking c = new Booking("Mei Lin");
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println("Bookings made so far: " + Booking.made());
}
}
class Booking {
private static int nextNumber = 1001;
private final int number;
private final String customer;
Booking(String customer) {
this.number = nextNumber;
nextNumber++;
this.customer = customer;
}
static int made() {
return nextNumber - 1001;
}
@Override
public String toString() {
return "#" + number + " " + customer;
}
}Bookings made so far: 0 #1001 Ana Ruiz #1002 Theo Park #1003 Mei Lin Bookings made so far: 3
What this code does
nextNumber is static, so all bookings share one counter, and each constructor takes the current value and moves it on. Each booking keeps its own number in an instance field, so the numbers stay different. made is a static method, called on the class name, and it works even before any booking exists.
Real systems usually let a database hand out numbers, which JAVA-250 covers, because a counter in memory starts again every time the program starts. For a single running program, a static counter is the simplest correct answer.
Calling static members
Call static members through the class name: Booking.made(), Math.max(a, b), Integer.parseInt(text). Java also allows calling them through an object reference, as in a.made(), but that is misleading, because it looks as if the result depends on a, and most tools warn about it. Inside the class itself the class name can be left off, which is why main could call helper methods directly in JAVA-101.
A static method has no this, because it is not running on any object. It therefore cannot use instance fields or call instance methods directly. This is the reason for the compile error beginners meet most often when they first add methods to Main.
public class Main {
private int bookingsToday = 4;
public static void main(String[] args) {
System.out.println("Bookings today: " + bookingsToday);
}
}What this code does
main is static, but bookingsToday is an instance field, so main has no object whose field it could read. javac reports that a non-static variable cannot be referenced from a static context. Either make the field static or create an object and read its field through a reference.
$ javac Main.java
Main.java:5: error: non-static variable bookingsToday cannot be referenced from a static context
System.out.println("Bookings today: " + bookingsToday);
^
1 errorConstants
A field that is both static and final is a constant: one shared value that never changes. Java convention writes constant names in capital letters with underscores, such as MAX_BOOKINGS_PER_DAY. Constants give numbers a name, so that the reader sees what 6 means and so that changing the rule means changing one line.
public class Main {
public static void main(String[] args) {
System.out.println(Rates.describe());
long subtotal = Rates.TUNE_UP_CENTS + 2 * Rates.TUBE_CENTS;
long tax = Rates.taxOn(subtotal);
System.out.println("Tune-up and two tubes: " + subtotal + " + " + tax + " tax = " + (subtotal + tax) + " cents");
}
}
class Rates {
static final long TUNE_UP_CENTS = 8500;
static final long TUBE_CENTS = 899;
static final int TAX_PER_HUNDRED = 8;
static final String TAX_NAME = "Sales tax";
static final int MAX_BOOKINGS_PER_DAY = 6;
static long taxOn(long cents) {
return (cents * TAX_PER_HUNDRED + 50) / 100;
}
static String describe() {
return TAX_NAME + " " + TAX_PER_HUNDRED + " in 100, at most " + MAX_BOOKINGS_PER_DAY + " repairs a day";
}
}Sales tax 8 in 100, at most 6 repairs a day Tune-up and two tubes: 10298 + 824 tax = 11122 cents
What this code does
Every price and rule in Rates is a static final constant with a capitalized name, so each number in the program has a meaning attached. taxOn adds 50 before dividing by 100 so the tax rounds to the nearest cent: 10,298 cents at 8 in 100 is 823.84, which rounds to 824. Changing the tax rate means changing one line.
A static final field that holds a mutable object, such as an array, is not truly constant: the reference cannot change, but the elements can. Prefer constants of primitive types, Strings and immutable objects, and lesson 9's enums for fixed sets of values.
Utility classes
Some methods do not belong to any object at all: they take some values and return a result. Math.max, Integer.parseInt and Arrays.sort are examples. Java collects such methods in utility classes, classes with only static members. A utility class should not be instantiated, since an object of it would hold nothing, so it is given a private constructor to stop new from being used. Many are also declared final so nobody can extend them.
public class Main {
public static void main(String[] args) {
System.out.println(Tags.forBooking(7, "Ana Ruiz"));
System.out.println(Tags.forBooking(1042, "theo park"));
System.out.println(Tags.isValid("SG-0007-AR"));
System.out.println(Tags.isValid("SG-7-AR"));
}
}
final class Tags {
private Tags() { } // no objects: this class only holds static helpers
static String forBooking(int number, String customer) {
return "SG-" + String.format("%04d", number) + "-" + initials(customer);
}
static boolean isValid(String tag) {
return tag.matches("SG-\\d{4}-[A-Z]{2,3}");
}
private static String initials(String name) {
StringBuilder sb = new StringBuilder();
for (String part : name.strip().split("\\s+")) {
sb.append(Character.toUpperCase(part.charAt(0)));
}
return sb.toString();
}
}SG-0007-AR SG-1042-TP true false
What this code does
Tags is a utility class: final, with a private constructor and only static methods, so it is used as Tags.forBooking without ever creating an object. forBooking pads the number to four digits and adds the customer's initials, and initials is a private helper used only inside the class. isValid checks a tag against a regular expression that requires SG, four digits and two or three capital letters.
The pattern inside isValid is a regular expression, a compact way of describing text: \d{4} means four digits and [A-Z]{2,3} means two or three capital letters. JAVA-230 covers regular expressions properly. The doubled backslashes are needed because a backslash in a Java String must itself be written with a backslash.
Useful utility classes in Java's library
Before writing a helper, check whether Java already has one. A few classes are worth knowing well.
| Class | Package | Some useful methods |
|---|---|---|
| Math | java.lang | max, min, abs, round, floorDiv, floorMod, sqrt, pow |
| Integer, Long, Double | java.lang | parseInt, valueOf, MAX_VALUE, compare |
| Character | java.lang | isDigit, isLetter, toUpperCase |
| String (static) | java.lang | valueOf, join, format |
| Arrays | java.util | sort, fill, copyOf, toString, equals, binarySearch |
| Objects | java.util | equals, hash, requireNonNull, toString(o, default) |
| Math.multiplyExact and friends | java.lang | arithmetic that throws instead of overflowing |
import java.util.Arrays;
import java.util.Objects;
public class Main {
public static void main(String[] args) {
int[] minutes = {45, 30, 90, 60};
Arrays.sort(minutes);
System.out.println("Sorted job times: " + Arrays.toString(minutes));
System.out.println("Longest: " + minutes[minutes.length - 1] + " min");
System.out.println("Hours, rounded up: " + Math.ceilDiv(Arrays.stream(minutes).sum(), 60));
String note = null;
System.out.println("Note: " + Objects.toString(note, "(none)"));
System.out.println("Same customer? " + Objects.equals("Ana Ruiz", "Ana Ruiz"));
System.out.println("Week of year 53 wraps to " + Math.floorMod(53, 52));
}
}Sorted job times: [30, 45, 60, 90] Longest: 90 min Hours, rounded up: 4 Note: (none) Same customer? true Week of year 53 wraps to 1
What this code does
Arrays.sort and Arrays.toString sort and print the job times, and Math.ceilDiv divides while rounding up, so 225 minutes needs 4 hours. Objects.toString prints a replacement when a value is null, and Objects.equals compares two values safely even if one is null. Math.floorMod gives the remainder that wraps round, which is always zero or positive.
Math.ceilDiv arrived in Java 18. Arrays.stream(minutes).sum() uses a stream to add the array; JAVA-230 explains streams, and a for loop does the same job.
Static initializer blocks
A static field can be given its starting value where it is declared. When the value needs several statements to work out, a static initializer block, written static { ... }, runs once when the class is first used. It is the static counterpart of the instance initializer block in lesson 3.
public class Main {
public static void main(String[] args) {
System.out.println("Main starts");
System.out.println("Slots on a weekday: " + Hours.slotsPerDay());
System.out.println("Opening hour: " + Hours.OPEN[0]);
}
}
class Hours {
static final int[] OPEN;
static {
System.out.println("Hours class loaded");
OPEN = new int[7];
for (int i = 0; i < OPEN.length; i++) {
OPEN[i] = 9 + i; // 9:00 to 15:00
}
}
static int slotsPerDay() {
return OPEN.length;
}
}Main starts Hours class loaded Slots on a weekday: 7 Opening hour: 9
What this code does
The static block runs once, the first time the program uses the Hours class, which is why Hours class loaded appears after Main starts. It fills the array of opening hours with a loop that a single initializer could not express. Later uses of Hours do not run the block again.
Keep static blocks short. Heavy work in them slows the moment a class is first used and makes errors hard to trace, because an exception there stops the class from loading at all.
Static nested classes
Lesson 3's Rental.Builder was a class declared inside another class with the word static. A static nested class is an ordinary class that happens to live inside another, used when it makes sense only together with its outer class. It is named Outer.Inner from outside and can use the outer class's private static members. Records and enums, from lesson 9, are often nested too.
public class Main {
public static void main(String[] args) {
Schedule.Entry e1 = new Schedule.Entry(9, "Ana Ruiz", "brake bleed");
Schedule.Entry e2 = new Schedule.Entry(14, "Theo Park", "wheel true");
Schedule day = new Schedule("2027-02-06", new Schedule.Entry[] {e1, e2});
day.print();
}
}
class Schedule {
private final String date;
private final Entry[] entries;
Schedule(String date, Entry[] entries) {
this.date = date;
this.entries = entries.clone();
}
void print() {
System.out.println("Schedule for " + date);
for (Entry e : entries) {
System.out.println(" " + e.label());
}
}
static class Entry {
private final int hour;
private final String customer;
private final String job;
Entry(int hour, String customer, String job) {
this.hour = hour;
this.customer = customer;
this.job = job;
}
String label() {
return String.format("%02d:00 %-10s %s", hour, customer, job);
}
}
}Schedule for 2027-02-06 09:00 Ana Ruiz brake bleed 14:00 Theo Park wheel true
What this code does
Entry is declared inside Schedule because a schedule entry makes no sense on its own. From main it is written Schedule.Entry, and it is an ordinary class with its own constructor and methods. Keeping it nested signals that it is part of Schedule's design.
Java also has inner classes, nested classes without static, whose objects are tied to an object of the outer class. They are less common in modern code and are not needed in this course; when in doubt, make a nested class static.
When static is the wrong choice
Because static methods are easy to call from anywhere, beginners sometimes make everything static, which brings back the JAVA-101 style this term is moving away from. Static mutable fields are especially risky: any code can change them, tests interfere with each other, and in programs with many threads, as in JAVA-240, they cause hard bugs. Use static for constants, for counters that truly belong to the class, for factory methods and for pure helpers that use only their parameters. Keep everything else in objects.
| Use static for | Avoid static for |
|---|---|
| Constants such as MAX_BOOKINGS_PER_DAY | Data that differs between objects |
| Pure helpers such as Tags.forBooking | Methods that need an object's state |
| Factory methods such as Money.ofCents | Global variables any code can change |
| A counter that belongs to the class | Saving the effort of passing a reference |
| main, which must be static | Hiding dependencies a class really has |
Try it yourself
A utility class
Write a utility class Sizes with a private constructor and a static method toInches(int cm) that converts a frame size in centimeters to whole inches, rounded to the nearest inch (1 inch is 2.54 cm).
Add a second static method fits(int frameCm, int heightCm) that returns true when the frame is between 0.32 and 0.36 of the rider's height, inclusive. The program should print 54 cm is 21 in, 56 cm is 22 in, true and false.
public class Main {
public static void main(String[] args) {
System.out.println("54 cm is " + Sizes.toInches(54) + " in");
System.out.println("56 cm is " + Sizes.toInches(56) + " in");
System.out.println(Sizes.fits(56, 165));
System.out.println(Sizes.fits(56, 190));
}
}
final class Sizes {
static int toInches(int cm) {
return 0;
}
static boolean fits(int frameCm, int heightCm) {
return false;
}
}Common mistakes
MistakeReading an instance field from main, which is static.
InsteadCreate an object and use its field, or make the value a static constant if it truly belongs to the class.
MistakeCalling a static method through an object, as a.made().
InsteadCall it through the class name, Booking.made(), so it is clear it does not depend on a.
MistakeLeaving a utility class with a public constructor.
InsteadGive it a private constructor so nobody creates useless objects.
MistakeMaking fields static to avoid passing objects around.
InsteadKeep per-object data in instance fields; static mutable data is shared by everything.
MistakeWriting a magic number such as 6 in several places.
InsteadDeclare a static final constant such as MAX_BOOKINGS_PER_DAY and use its name.
Summary and key terms
- Instance fields and methods belong to each object; static fields and methods belong to the class, with one shared copy.
- A static counter can give every object a unique number.
- Static members are called through the class name, and static methods have no this, so they cannot use instance fields directly. static final fields are constants, named in capitals, and they give numbers meaning in one place.
- Utility classes hold only static helpers, have a private constructor and are often final; Java's Math, Arrays, Objects and the wrapper classes are examples worth knowing.
- A static initializer block runs once when a class is first used.
- A static nested class lives inside another class because it belongs to its design.
- Use static for constants, pure helpers, factories and class-wide counters, not as a shortcut around passing objects.
- Static field
- A field that belongs to the class, with one copy shared by all objects.
- Static method
- A method that belongs to the class and runs without a current object.
- Instance member
- A field or method that belongs to each object.
- Constant
- A static final field whose value never changes.
- Utility class
- A class of static helper methods that is never instantiated.
- Private constructor
- A constructor that only code inside the class can call.
- Static initializer block
- A block, written static { }, that runs once when a class is first used.
- Static nested class
- A class declared inside another with the word static.
- Regular expression
- A pattern that describes a set of text strings.
Practice problems
Work each problem on paper first, then reveal the answer to check.
How many copies of a static field exist when there are 50 objects?
Show answer
One, shared by the class.
Why can main not read an instance field directly?
Show answer
main is static and has no current object whose field it could read.
How do you stop a utility class from being instantiated?
Show answer
Give it a private constructor.
When does a static initializer block run?
Show answer
Once, the first time the class is used.
What rounding does taxOn use when it adds 50 before dividing by 100?
Show answer
It rounds to the nearest cent.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.